blob: bef4f5a847f3daa1dfe9fd5fcda30527ad2e301f [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;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800120import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800125import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100137import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400144import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.Notification;
147import android.app.NotificationManager;
148import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.PictureInPictureParams;
150import android.app.ProfilerInfo;
151import android.app.RemoteAction;
152import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700153import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.admin.DevicePolicyCache;
155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100196import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900212import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100215import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700217import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.EventLog;
219import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700220import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700222import android.util.SparseIntArray;
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 Ogunwale53783742018-09-16 10:21:51 -0700249import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700292import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700294import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700295import java.util.Map;
296import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297
298/**
299 * System service for managing activities and their containers (task, stacks, displays,... ).
300 *
301 * {@hide}
302 */
303public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700305 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700306 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
307 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
308 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
309 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
310 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700311 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700312
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100317 // How long we permit background activity starts after an activity in the process
318 // started or finished.
319 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320
Wale Ogunwale98875612018-10-12 07:53:02 -0700321 /** Used to indicate that an app transition should be animated. */
322 static final boolean ANIMATE = true;
323
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700324 /** Hardware-reported OpenGLES version. */
325 final int GL_ES_VERSION;
326
Wale Ogunwale31913b52018-10-13 08:29:31 -0700327 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
328 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
329 public static final String DUMP_LASTANR_CMD = "lastanr" ;
330 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
331 public static final String DUMP_STARTER_CMD = "starter" ;
332 public static final String DUMP_CONTAINERS_CMD = "containers" ;
333 public static final String DUMP_RECENTS_CMD = "recents" ;
334 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
335
Wale Ogunwale64258362018-10-16 15:13:37 -0700336 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
337 public static final int RELAUNCH_REASON_NONE = 0;
338 /** This activity is being relaunched due to windowing mode change. */
339 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
340 /** This activity is being relaunched due to a free-resize operation. */
341 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
342
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700343 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700344
Wale Ogunwalef6733932018-06-27 05:14:34 -0700345 /**
346 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
347 * change at runtime. Use mContext for non-UI purposes.
348 */
349 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700351 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700354 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700355 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800356 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800357 @VisibleForTesting
358 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 PowerManagerInternal mPowerManagerInternal;
360 private UsageStatsManagerInternal mUsageStatsInternal;
361
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700362 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 IntentFirewall mIntentFirewall;
364
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700365 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800366 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700368 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
370 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
371 *
372 * @see WindowManagerThreadPriorityBooster
373 */
374 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800376 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700377 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private UserManagerService mUserManager;
379 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700380 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800381 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700382 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** All processes currently running that might have a window organized by name. */
384 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100385 /** All processes we currently have running mapped by pid and uid */
386 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** This is the process holding what we currently consider to be the "home" activity. */
388 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700389 /** The currently running heavy-weight process, if any. */
390 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700391 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /**
393 * This is the process holding the activity the user last visited that is in a different process
394 * from the one they are currently in.
395 */
396 WindowProcessController mPreviousProcess;
397 /** The time at which the previous process was last visible. */
398 long mPreviousProcessVisibleTime;
399
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700400 /** List of intents that were used to start the most recent tasks. */
401 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700402 /** State of external calls telling us if the device is awake or asleep. */
403 private boolean mKeyguardShown = false;
404
405 // Wrapper around VoiceInteractionServiceManager
406 private AssistUtils mAssistUtils;
407
408 // VoiceInteraction session ID that changes for each new request except when
409 // being called for multi-window assist in a single session.
410 private int mViSessionId = 1000;
411
412 // How long to wait in getAssistContextExtras for the activity and foreground services
413 // to respond with the result.
414 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
415
416 // How long top wait when going through the modern assist (which doesn't need to block
417 // on getting this result before starting to launch its UI).
418 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
419
420 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
421 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
422
Alison Cichowlas3e340502018-08-07 17:15:01 -0400423 // Permission tokens are used to temporarily granted a trusted app the ability to call
424 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
425 // showing any appropriate error messages to the user.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
427 10 * MINUTE_IN_MILLIS;
428
429 // How long before the service actually expires a token. This is slightly longer than
430 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
431 // expiration exception.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
433 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
434
435 // How long the service will remember expired tokens, for the purpose of providing error
436 // messaging when a client uses an expired token.
437 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
438 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
439
440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700466 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700553
554 /**
555 * Flag that indicates if multi-window is enabled.
556 *
557 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
558 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
559 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
560 * At least one of the forms of multi-window must be enabled in order for this flag to be
561 * initialized to 'true'.
562 *
563 * @see #mSupportsSplitScreenMultiWindow
564 * @see #mSupportsFreeformWindowManagement
565 * @see #mSupportsPictureInPicture
566 * @see #mSupportsMultiDisplay
567 */
568 boolean mSupportsMultiWindow;
569 boolean mSupportsSplitScreenMultiWindow;
570 boolean mSupportsFreeformWindowManagement;
571 boolean mSupportsPictureInPicture;
572 boolean mSupportsMultiDisplay;
573 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700574 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
Riddle Hsua0022cd2019-09-09 21:12:41 +0800602 @Retention(RetentionPolicy.SOURCE)
603 @IntDef({
604 LAYOUT_REASON_CONFIG_CHANGED,
605 LAYOUT_REASON_VISIBILITY_CHANGED,
606 })
607 @interface LayoutReason {}
608 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
609 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
610
611 /** The reasons to perform surface placement. */
612 @LayoutReason
613 private int mLayoutReasons;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
616 // automatically. Important for devices without direct input devices.
617 private boolean mShowDialogs = true;
618
619 /** Set if we are shutting down the system, similar to sleeping. */
620 boolean mShuttingDown = false;
621
622 /**
623 * We want to hold a wake lock while running a voice interaction session, since
624 * this may happen with the screen off and we need to keep the CPU running to
625 * be able to continue to interact with the user.
626 */
627 PowerManager.WakeLock mVoiceWakeLock;
628
629 /**
630 * Set while we are running a voice interaction. This overrides sleeping while it is active.
631 */
632 IVoiceInteractionSession mRunningVoice;
633
634 /**
635 * The last resumed activity. This is identical to the current resumed activity most
636 * of the time but could be different when we're pausing one activity before we resume
637 * another activity.
638 */
639 ActivityRecord mLastResumedActivity;
640
641 /**
642 * The activity that is currently being traced as the active resumed activity.
643 *
644 * @see #updateResumedAppTrace
645 */
646 private @Nullable ActivityRecord mTracedResumedActivity;
647
648 /** If non-null, we are tracking the time the user spends in the currently focused app. */
649 AppTimeTracker mCurAppTimeTracker;
650
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700651 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700652
Wale Ogunwale53783742018-09-16 10:21:51 -0700653 /**
654 * Packages that the user has asked to have run in screen size
655 * compatibility mode instead of filling the screen.
656 */
657 CompatModePackages mCompatModePackages;
658
Wale Ogunwalef6733932018-06-27 05:14:34 -0700659 private FontScaleSettingObserver mFontScaleSettingObserver;
660
Ricky Wai96f5c352019-04-10 18:40:17 +0100661 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000662
Wale Ogunwalef6733932018-06-27 05:14:34 -0700663 private final class FontScaleSettingObserver extends ContentObserver {
664 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
665 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
666
667 public FontScaleSettingObserver() {
668 super(mH);
669 final ContentResolver resolver = mContext.getContentResolver();
670 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
671 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
672 UserHandle.USER_ALL);
673 }
674
675 @Override
676 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
677 if (mFontScaleUri.equals(uri)) {
678 updateFontScaleIfNeeded(userId);
679 } else if (mHideErrorDialogsUri.equals(uri)) {
680 synchronized (mGlobalLock) {
681 updateShouldShowDialogsLocked(getGlobalConfiguration());
682 }
683 }
684 }
685 }
686
Riddle Hsua0536432019-02-16 00:38:59 +0800687 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
688 @Target(ElementType.METHOD)
689 @Retention(RetentionPolicy.SOURCE)
690 @interface HotPath {
691 int NONE = 0;
692 int OOM_ADJUSTMENT = 1;
693 int LRU_UPDATE = 2;
694 int PROCESS_CHANGE = 3;
695 int caller() default NONE;
696 }
697
Charles Chen8d98dd22018-12-26 17:36:54 +0800698 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
699 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700700 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700701 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700702 mSystemThread = ActivityThread.currentActivityThread();
703 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700704 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800705 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700706 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700707 }
708
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700709 public void onSystemReady() {
710 synchronized (mGlobalLock) {
711 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
712 PackageManager.FEATURE_CANT_SAVE_STATE);
713 mAssistUtils = new AssistUtils(mContext);
714 mVrController.onSystemReady();
715 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700716 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700718 }
719
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700720 public void onInitPowerManagement() {
721 synchronized (mGlobalLock) {
722 mStackSupervisor.initPowerManagement();
723 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
724 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
725 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
726 mVoiceWakeLock.setReferenceCounted(false);
727 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700731 mFontScaleSettingObserver = new FontScaleSettingObserver();
732 }
733
Wale Ogunwale59507092018-10-29 09:00:30 -0700734 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 final boolean freeformWindowManagement =
736 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
737 || Settings.Global.getInt(
738 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
739
740 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
741 final boolean supportsPictureInPicture = supportsMultiWindow &&
742 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
743 final boolean supportsSplitScreenMultiWindow =
744 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
745 final boolean supportsMultiDisplay = mContext.getPackageManager()
746 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
748 final boolean forceResizable = Settings.Global.getInt(
749 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700750 final boolean sizeCompatFreeform = Settings.Global.getInt(
751 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700752
753 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900754 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700755
756 final Configuration configuration = new Configuration();
757 Settings.System.getConfiguration(resolver, configuration);
758 if (forceRtl) {
759 // This will take care of setting the correct layout direction flags
760 configuration.setLayoutDirection(configuration.locale);
761 }
762
763 synchronized (mGlobalLock) {
764 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700765 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766 final boolean multiWindowFormEnabled = freeformWindowManagement
767 || supportsSplitScreenMultiWindow
768 || supportsPictureInPicture
769 || supportsMultiDisplay;
770 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
771 mSupportsMultiWindow = true;
772 mSupportsFreeformWindowManagement = freeformWindowManagement;
773 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
774 mSupportsPictureInPicture = supportsPictureInPicture;
775 mSupportsMultiDisplay = supportsMultiDisplay;
776 } else {
777 mSupportsMultiWindow = false;
778 mSupportsFreeformWindowManagement = false;
779 mSupportsSplitScreenMultiWindow = false;
780 mSupportsPictureInPicture = false;
781 mSupportsMultiDisplay = false;
782 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700783 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700784 // This happens before any activities are started, so we can change global configuration
785 // in-place.
786 updateConfigurationLocked(configuration, null, true);
787 final Configuration globalConfig = getGlobalConfiguration();
788 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
789
790 // Load resources only after the current configuration has been set.
791 final Resources res = mContext.getResources();
792 mThumbnailWidth = res.getDimensionPixelSize(
793 com.android.internal.R.dimen.thumbnail_width);
794 mThumbnailHeight = res.getDimensionPixelSize(
795 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700796 }
797 }
798
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800799 public WindowManagerGlobalLock getGlobalLock() {
800 return mGlobalLock;
801 }
802
Yunfan Chen585f2932019-01-29 16:04:45 +0900803 /** For test purpose only. */
804 @VisibleForTesting
805 public ActivityTaskManagerInternal getAtmInternal() {
806 return mInternal;
807 }
808
Riddle Hsud93a6c42018-11-29 21:50:06 +0800809 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
810 Looper looper) {
811 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700812 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700813 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700814 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800815 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700816 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700817 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818
819 mTempConfig.setToDefaults();
820 mTempConfig.setLocales(LocaleList.getDefault());
821 mConfigurationSeq = mTempConfig.seq = 1;
822 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800823 mRootActivityContainer = new RootActivityContainer(this);
824 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700825
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700826 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700827 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700828 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700830 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mKeyguardController = mStackSupervisor.getKeyguardController();
833 }
834
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700835 public void onActivityManagerInternalAdded() {
836 synchronized (mGlobalLock) {
837 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
838 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
839 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700840 }
841
Yunfan Chen75157d72018-07-27 14:47:21 +0900842 int increaseConfigurationSeqLocked() {
843 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
844 return mConfigurationSeq;
845 }
846
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700847 protected ActivityStackSupervisor createStackSupervisor() {
848 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
849 supervisor.initialize();
850 return supervisor;
851 }
852
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800853 protected AppWarnings createAppWarnings(
854 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
855 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
856 }
857
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 public void setWindowManager(WindowManagerService wm) {
859 synchronized (mGlobalLock) {
860 mWindowManager = wm;
861 mLockTaskController.setWindowManager(wm);
862 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800863 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700864 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700865 }
866
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700867 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
868 synchronized (mGlobalLock) {
869 mUsageStatsInternal = usageStatsManager;
870 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700871 }
872
Wale Ogunwalef6733932018-06-27 05:14:34 -0700873 UserManagerService getUserManager() {
874 if (mUserManager == null) {
875 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
876 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
877 }
878 return mUserManager;
879 }
880
881 AppOpsService getAppOpsService() {
882 if (mAppOpsService == null) {
883 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
884 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
885 }
886 return mAppOpsService;
887 }
888
889 boolean hasUserRestriction(String restriction, int userId) {
890 return getUserManager().hasUserRestriction(restriction, userId);
891 }
892
Michal Karpinski15486842019-04-25 17:33:42 +0100893 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
894 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700895 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100896 if (mode == AppOpsManager.MODE_DEFAULT) {
897 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
898 == PERMISSION_GRANTED;
899 }
900 return mode == AppOpsManager.MODE_ALLOWED;
901 }
902
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700903 @VisibleForTesting
904 protected void setRecentTasks(RecentTasks recentTasks) {
905 mRecentTasks = recentTasks;
906 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700907 }
908
909 RecentTasks getRecentTasks() {
910 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700911 }
912
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700913 ClientLifecycleManager getLifecycleManager() {
914 return mLifecycleManager;
915 }
916
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700917 ActivityStartController getActivityStartController() {
918 return mActivityStartController;
919 }
920
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700921 TaskChangeNotificationController getTaskChangeNotificationController() {
922 return mTaskChangeNotificationController;
923 }
924
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700925 LockTaskController getLockTaskController() {
926 return mLockTaskController;
927 }
928
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 /**
930 * Return the global configuration used by the process corresponding to the input pid. This is
931 * usually the global configuration with some overrides specific to that process.
932 */
933 Configuration getGlobalConfigurationForCallingPid() {
934 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800935 return getGlobalConfigurationForPid(pid);
936 }
937
938 /**
939 * Return the global configuration used by the process corresponding to the given pid.
940 */
941 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 if (pid == MY_PID || pid < 0) {
943 return getGlobalConfiguration();
944 }
945 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100946 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900947 return app != null ? app.getConfiguration() : getGlobalConfiguration();
948 }
949 }
950
951 /**
952 * Return the device configuration info used by the process corresponding to the input pid.
953 * The value is consistent with the global configuration for the process.
954 */
955 @Override
956 public ConfigurationInfo getDeviceConfigurationInfo() {
957 ConfigurationInfo config = new ConfigurationInfo();
958 synchronized (mGlobalLock) {
959 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
960 config.reqTouchScreen = globalConfig.touchscreen;
961 config.reqKeyboardType = globalConfig.keyboard;
962 config.reqNavigation = globalConfig.navigation;
963 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
964 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
965 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
966 }
967 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
968 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
969 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
970 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700971 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900972 }
973 return config;
974 }
975
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700976 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700977 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700978 }
979
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 public static final class Lifecycle extends SystemService {
981 private final ActivityTaskManagerService mService;
982
983 public Lifecycle(Context context) {
984 super(context);
985 mService = new ActivityTaskManagerService(context);
986 }
987
988 @Override
989 public void onStart() {
990 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 }
993
Garfield Tan891146c2018-10-09 12:14:00 -0700994 @Override
995 public void onUnlockUser(int userId) {
996 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800997 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700998 }
999 }
1000
1001 @Override
1002 public void onCleanupUser(int userId) {
1003 synchronized (mService.getGlobalLock()) {
1004 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1005 }
1006 }
1007
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001008 public ActivityTaskManagerService getService() {
1009 return mService;
1010 }
1011 }
1012
1013 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001014 public final int startActivity(IApplicationThread caller, String callingPackage,
1015 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1016 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1017 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1018 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1019 UserHandle.getCallingUserId());
1020 }
1021
1022 @Override
1023 public final int startActivities(IApplicationThread caller, String callingPackage,
1024 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1025 int userId) {
1026 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001027 enforceNotIsolatedCaller(reason);
1028 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001030 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1031 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1032 reason, null /* originatingPendingIntent */,
1033 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 }
1035
1036 @Override
1037 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1038 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1039 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1040 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1041 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1042 true /*validateIncomingUser*/);
1043 }
1044
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001045 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1047 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1048 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001049 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001051 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1053
1054 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001055 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 .setCaller(caller)
1057 .setCallingPackage(callingPackage)
1058 .setResolvedType(resolvedType)
1059 .setResultTo(resultTo)
1060 .setResultWho(resultWho)
1061 .setRequestCode(requestCode)
1062 .setStartFlags(startFlags)
1063 .setProfilerInfo(profilerInfo)
1064 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001065 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .execute();
1067
1068 }
1069
1070 @Override
1071 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1072 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001073 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1074 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 // Refuse possible leaked file descriptors
1076 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1077 throw new IllegalArgumentException("File descriptors passed in Intent");
1078 }
1079
1080 if (!(target instanceof PendingIntentRecord)) {
1081 throw new IllegalArgumentException("Bad PendingIntent object");
1082 }
1083
1084 PendingIntentRecord pir = (PendingIntentRecord)target;
1085
1086 synchronized (mGlobalLock) {
1087 // If this is coming from the currently resumed activity, it is
1088 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001089 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 if (stack.mResumedActivity != null &&
1091 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001092 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001093 }
1094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001095 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 }
1098
1099 @Override
1100 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1101 Bundle bOptions) {
1102 // Refuse possible leaked file descriptors
1103 if (intent != null && intent.hasFileDescriptors()) {
1104 throw new IllegalArgumentException("File descriptors passed in Intent");
1105 }
1106 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1107
1108 synchronized (mGlobalLock) {
1109 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1110 if (r == null) {
1111 SafeActivityOptions.abort(options);
1112 return false;
1113 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001114 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001115 // The caller is not running... d'oh!
1116 SafeActivityOptions.abort(options);
1117 return false;
1118 }
1119 intent = new Intent(intent);
1120 // The caller is not allowed to change the data.
1121 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1122 // And we are resetting to find the next component...
1123 intent.setComponent(null);
1124
1125 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1126
1127 ActivityInfo aInfo = null;
1128 try {
1129 List<ResolveInfo> resolves =
1130 AppGlobals.getPackageManager().queryIntentActivities(
1131 intent, r.resolvedType,
1132 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1133 UserHandle.getCallingUserId()).getList();
1134
1135 // Look for the original activity in the list...
1136 final int N = resolves != null ? resolves.size() : 0;
1137 for (int i=0; i<N; i++) {
1138 ResolveInfo rInfo = resolves.get(i);
1139 if (rInfo.activityInfo.packageName.equals(r.packageName)
1140 && rInfo.activityInfo.name.equals(r.info.name)) {
1141 // We found the current one... the next matching is
1142 // after it.
1143 i++;
1144 if (i<N) {
1145 aInfo = resolves.get(i).activityInfo;
1146 }
1147 if (debug) {
1148 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1149 + "/" + r.info.name);
1150 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1151 ? "null" : aInfo.packageName + "/" + aInfo.name));
1152 }
1153 break;
1154 }
1155 }
1156 } catch (RemoteException e) {
1157 }
1158
1159 if (aInfo == null) {
1160 // Nobody who is next!
1161 SafeActivityOptions.abort(options);
1162 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1163 return false;
1164 }
1165
1166 intent.setComponent(new ComponentName(
1167 aInfo.applicationInfo.packageName, aInfo.name));
1168 intent.setFlags(intent.getFlags()&~(
1169 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1170 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1171 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1172 FLAG_ACTIVITY_NEW_TASK));
1173
1174 // Okay now we need to start the new activity, replacing the currently running activity.
1175 // This is a little tricky because we want to start the new one as if the current one is
1176 // finished, but not finish the current one first so that there is no flicker.
1177 // And thus...
1178 final boolean wasFinishing = r.finishing;
1179 r.finishing = true;
1180
1181 // Propagate reply information over to the new activity.
1182 final ActivityRecord resultTo = r.resultTo;
1183 final String resultWho = r.resultWho;
1184 final int requestCode = r.requestCode;
1185 r.resultTo = null;
1186 if (resultTo != null) {
1187 resultTo.removeResultsLocked(r, resultWho, requestCode);
1188 }
1189
1190 final long origId = Binder.clearCallingIdentity();
1191 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001192 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001193 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001194 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001195 .setResolvedType(r.resolvedType)
1196 .setActivityInfo(aInfo)
1197 .setResultTo(resultTo != null ? resultTo.appToken : null)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setCallingPid(-1)
1201 .setCallingUid(r.launchedFromUid)
1202 .setCallingPackage(r.launchedFromPackage)
1203 .setRealCallingPid(-1)
1204 .setRealCallingUid(r.launchedFromUid)
1205 .setActivityOptions(options)
1206 .execute();
1207 Binder.restoreCallingIdentity(origId);
1208
1209 r.finishing = wasFinishing;
1210 if (res != ActivityManager.START_SUCCESS) {
1211 return false;
1212 }
1213 return true;
1214 }
1215 }
1216
1217 @Override
1218 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1219 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1220 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1221 final WaitResult res = new WaitResult();
1222 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001223 enforceNotIsolatedCaller("startActivityAndWait");
1224 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1225 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001226 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001227 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 .setCaller(caller)
1229 .setCallingPackage(callingPackage)
1230 .setResolvedType(resolvedType)
1231 .setResultTo(resultTo)
1232 .setResultWho(resultWho)
1233 .setRequestCode(requestCode)
1234 .setStartFlags(startFlags)
1235 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001236 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setProfilerInfo(profilerInfo)
1238 .setWaitResult(res)
1239 .execute();
1240 }
1241 return res;
1242 }
1243
1244 @Override
1245 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1246 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1247 int startFlags, Configuration config, Bundle bOptions, int userId) {
1248 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001249 enforceNotIsolatedCaller("startActivityWithConfig");
1250 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1251 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001252 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001253 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001254 .setCaller(caller)
1255 .setCallingPackage(callingPackage)
1256 .setResolvedType(resolvedType)
1257 .setResultTo(resultTo)
1258 .setResultWho(resultWho)
1259 .setRequestCode(requestCode)
1260 .setStartFlags(startFlags)
1261 .setGlobalConfiguration(config)
1262 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001263 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 .execute();
1265 }
1266 }
1267
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268
1269 @Override
1270 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1271 int callingUid = Binder.getCallingUid();
1272 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1273 throw new SecurityException("Only the system process can request a permission token, "
1274 + "received request from uid: " + callingUid);
1275 }
1276 IBinder permissionToken = new Binder();
1277 synchronized (mGlobalLock) {
1278 mStartActivitySources.put(permissionToken, delegatorToken);
1279 }
1280
1281 Message expireMsg = PooledLambda.obtainMessage(
1282 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1283 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1284
1285 Message forgetMsg = PooledLambda.obtainMessage(
1286 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1287 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1288
1289 return permissionToken;
1290 }
1291
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 @Override
1293 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1294 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1296 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001298 // permission grants) as any app that may launch one of your own activities. So we only
1299 // allow this in two cases:
1300 // 1) The caller is an activity that is part of the core framework, and then only when it
1301 // is running as the system.
1302 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1303 // can only be requested by a system activity, which may then delegate this call to
1304 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 final ActivityRecord sourceRecord;
1306 final int targetUid;
1307 final String targetPackage;
1308 final boolean isResolver;
1309 synchronized (mGlobalLock) {
1310 if (resultTo == null) {
1311 throw new SecurityException("Must be called from an activity");
1312 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001313 final IBinder sourceToken;
1314 if (permissionToken != null) {
1315 // To even attempt to use a permissionToken, an app must also have this signature
1316 // permission.
1317 mAmInternal.enforceCallingPermission(
1318 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1319 "startActivityAsCaller");
1320 // If called with a permissionToken, we want the sourceRecord from the delegator
1321 // activity that requested this token.
1322 sourceToken = mStartActivitySources.remove(permissionToken);
1323 if (sourceToken == null) {
1324 // Invalid permissionToken, check if it recently expired.
1325 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1326 throw new SecurityException("Called with expired permission token: "
1327 + permissionToken);
1328 } else {
1329 throw new SecurityException("Called with invalid permission token: "
1330 + permissionToken);
1331 }
1332 }
1333 } else {
1334 // This method was called directly by the source.
1335 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001337
Wale Ogunwaled32da472018-11-16 07:19:28 -08001338 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339 if (sourceRecord == null) {
1340 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 }
1342 if (sourceRecord.app == null) {
1343 throw new SecurityException("Called without a process attached to activity");
1344 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345
1346 // Whether called directly or from a delegate, the source activity must be from the
1347 // android package.
1348 if (!sourceRecord.info.packageName.equals("android")) {
1349 throw new SecurityException("Must be called from an activity that is "
1350 + "declared in the android package");
1351 }
1352
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001353 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 // This is still okay, as long as this activity is running under the
1355 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001356 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001358 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 + " must be system uid or original calling uid "
1360 + sourceRecord.launchedFromUid);
1361 }
1362 }
1363 if (ignoreTargetSecurity) {
1364 if (intent.getComponent() == null) {
1365 throw new SecurityException(
1366 "Component must be specified with ignoreTargetSecurity");
1367 }
1368 if (intent.getSelector() != null) {
1369 throw new SecurityException(
1370 "Selector not allowed with ignoreTargetSecurity");
1371 }
1372 }
1373 targetUid = sourceRecord.launchedFromUid;
1374 targetPackage = sourceRecord.launchedFromPackage;
1375 isResolver = sourceRecord.isResolverOrChildActivity();
1376 }
1377
1378 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001379 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 }
1381
1382 // TODO: Switch to user app stacks here.
1383 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001384 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 .setCallingUid(targetUid)
1386 .setCallingPackage(targetPackage)
1387 .setResolvedType(resolvedType)
1388 .setResultTo(resultTo)
1389 .setResultWho(resultWho)
1390 .setRequestCode(requestCode)
1391 .setStartFlags(startFlags)
1392 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001393 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1395 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001396 // The target may well be in the background, which would normally prevent it
1397 // from starting an activity. Here we definitely want the start to succeed.
1398 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 .execute();
1400 } catch (SecurityException e) {
1401 // XXX need to figure out how to propagate to original app.
1402 // A SecurityException here is generally actually a fault of the original
1403 // calling activity (such as a fairly granting permissions), so propagate it
1404 // back to them.
1405 /*
1406 StringBuilder msg = new StringBuilder();
1407 msg.append("While launching");
1408 msg.append(intent.toString());
1409 msg.append(": ");
1410 msg.append(e.getMessage());
1411 */
1412 throw e;
1413 }
1414 }
1415
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1417 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1418 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1419 }
1420
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 @Override
1422 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1423 Intent intent, String resolvedType, IVoiceInteractionSession session,
1424 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1425 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001426 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 if (session == null || interactor == null) {
1428 throw new NullPointerException("null session or interactor");
1429 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001432 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 .setCallingUid(callingUid)
1434 .setCallingPackage(callingPackage)
1435 .setResolvedType(resolvedType)
1436 .setVoiceSession(session)
1437 .setVoiceInteractor(interactor)
1438 .setStartFlags(startFlags)
1439 .setProfilerInfo(profilerInfo)
1440 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001441 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001442 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .execute();
1444 }
1445
1446 @Override
1447 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1448 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1450 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001452 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 .setCallingUid(callingUid)
1454 .setCallingPackage(callingPackage)
1455 .setResolvedType(resolvedType)
1456 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001457 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001458 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .execute();
1460 }
1461
Riddle Hsu609a8e22019-06-27 16:46:29 -06001462 /**
1463 * Start the recents activity to perform the recents animation.
1464 *
1465 * @param intent The intent to start the recents activity.
1466 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1467 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1470 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001471 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001473 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 final long origId = Binder.clearCallingIdentity();
1475 try {
1476 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001477 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1478 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480
1481 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001482 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001484 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001485 if (recentsAnimationRunner == null) {
1486 anim.preloadRecentsActivity();
1487 } else {
1488 anim.startRecentsActivity(recentsAnimationRunner);
1489 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001490 }
1491 } finally {
1492 Binder.restoreCallingIdentity(origId);
1493 }
1494 }
1495
1496 @Override
1497 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 "startActivityFromRecents()");
1500
1501 final int callingPid = Binder.getCallingPid();
1502 final int callingUid = Binder.getCallingUid();
1503 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1504 final long origId = Binder.clearCallingIdentity();
1505 try {
1506 synchronized (mGlobalLock) {
1507 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1508 safeOptions);
1509 }
1510 } finally {
1511 Binder.restoreCallingIdentity(origId);
1512 }
1513 }
1514
1515 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001516 * Public API to check if the client is allowed to start an activity on specified display.
1517 *
1518 * If the target display is private or virtual, some restrictions will apply.
1519 *
1520 * @param displayId Target display id.
1521 * @param intent Intent used to launch the activity.
1522 * @param resolvedType The MIME type of the intent.
1523 * @param userId The id of the user for whom the call is made.
1524 * @return {@code true} if a call to start an activity on the target display should succeed and
1525 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1526 */
1527 @Override
1528 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1529 String resolvedType, int userId) {
1530 final int callingUid = Binder.getCallingUid();
1531 final int callingPid = Binder.getCallingPid();
1532 final long origId = Binder.clearCallingIdentity();
1533
1534 try {
1535 // Collect information about the target of the Intent.
1536 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1537 0 /* startFlags */, null /* profilerInfo */, userId,
1538 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1539 UserHandle.USER_NULL));
1540 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1541
1542 synchronized (mGlobalLock) {
1543 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1544 aInfo);
1545 }
1546 } finally {
1547 Binder.restoreCallingIdentity(origId);
1548 }
1549 }
1550
1551 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 * This is the internal entry point for handling Activity.finish().
1553 *
1554 * @param token The Binder token referencing the Activity we want to finish.
1555 * @param resultCode Result code, if any, from this Activity.
1556 * @param resultData Result data (Intent), if any, from this Activity.
1557 * @param finishTask Whether to finish the task associated with this Activity.
1558 *
1559 * @return Returns true if the activity successfully finished, or false if it is still running.
1560 */
1561 @Override
1562 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1563 int finishTask) {
1564 // Refuse possible leaked file descriptors
1565 if (resultData != null && resultData.hasFileDescriptors()) {
1566 throw new IllegalArgumentException("File descriptors passed in Intent");
1567 }
1568
1569 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001570 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (r == null) {
1572 return true;
1573 }
1574 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001575 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001576 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (rootR == null) {
1578 Slog.w(TAG, "Finishing task with all activities already finished");
1579 }
1580 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1581 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001582 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 return false;
1584 }
1585
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001586 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1587 // We should consolidate.
1588 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001590 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (next != null) {
1592 // ask watcher if this is allowed
1593 boolean resumeOK = true;
1594 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001595 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001597 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 Watchdog.getInstance().setActivityController(null);
1599 }
1600
1601 if (!resumeOK) {
1602 Slog.i(TAG, "Not finishing activity because controller resumed");
1603 return false;
1604 }
1605 }
1606 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001607
1608 // note down that the process has finished an activity and is in background activity
1609 // starts grace period
1610 if (r.app != null) {
1611 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1612 }
1613
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001614 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001615 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 try {
1617 boolean res;
1618 final boolean finishWithRootActivity =
1619 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1620 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1621 || (finishWithRootActivity && r == rootR)) {
1622 // If requested, remove the task that is associated to this activity only if it
1623 // was the root activity in the task. The result code and data is ignored
1624 // because we don't support returning them across task boundaries. Also, to
1625 // keep backwards compatibility we remove the task from recents when finishing
1626 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001627 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 finishWithRootActivity, "finish-activity");
1629 if (!res) {
1630 Slog.i(TAG, "Removing task failed to finish activity");
1631 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001632 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001633 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001635 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001636 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 if (!res) {
1638 Slog.i(TAG, "Failed to finish by app-request");
1639 }
1640 }
1641 return res;
1642 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001643 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 Binder.restoreCallingIdentity(origId);
1645 }
1646 }
1647 }
1648
1649 @Override
1650 public boolean finishActivityAffinity(IBinder token) {
1651 synchronized (mGlobalLock) {
1652 final long origId = Binder.clearCallingIdentity();
1653 try {
1654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r == null) {
1656 return false;
1657 }
1658
1659 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1660 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001661 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 return false;
1663 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001664 r.finishActivityAffinity();
1665 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 } finally {
1667 Binder.restoreCallingIdentity(origId);
1668 }
1669 }
1670 }
1671
1672 @Override
1673 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1674 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001675 try {
1676 WindowProcessController proc = null;
1677 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001678 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001679 ActivityStack stack = ActivityRecord.getStackLocked(token);
1680 if (stack == null) {
1681 return;
1682 }
1683 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1684 false /* fromTimeout */, false /* processPausingActivities */, config);
1685 if (r != null) {
1686 proc = r.app;
1687 }
1688 if (stopProfiling && proc != null) {
1689 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 }
1691 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001692 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001693 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001694 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 }
1697
1698 @Override
1699 public final void activityResumed(IBinder token) {
1700 final long origId = Binder.clearCallingIdentity();
1701 synchronized (mGlobalLock) {
1702 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 }
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001708 public final void activityTopResumedStateLost() {
1709 final long origId = Binder.clearCallingIdentity();
1710 synchronized (mGlobalLock) {
1711 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1712 }
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715
1716 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 public final void activityPaused(IBinder token) {
1718 final long origId = Binder.clearCallingIdentity();
1719 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001720 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 ActivityStack stack = ActivityRecord.getStackLocked(token);
1722 if (stack != null) {
1723 stack.activityPausedLocked(token, false);
1724 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001725 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 }
1727 Binder.restoreCallingIdentity(origId);
1728 }
1729
1730 @Override
1731 public final void activityStopped(IBinder token, Bundle icicle,
1732 PersistableBundle persistentState, CharSequence description) {
1733 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1734
1735 // Refuse possible leaked file descriptors
1736 if (icicle != null && icicle.hasFileDescriptors()) {
1737 throw new IllegalArgumentException("File descriptors passed in Bundle");
1738 }
1739
1740 final long origId = Binder.clearCallingIdentity();
1741
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001742 String restartingName = null;
1743 int restartingUid = 0;
1744 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001746 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001747 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001749 if (r.attachedToProcess()
1750 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1751 // The activity was requested to restart from
1752 // {@link #restartActivityProcessIfVisible}.
1753 restartingName = r.app.mName;
1754 restartingUid = r.app.mUid;
1755 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 r.activityStoppedLocked(icicle, persistentState, description);
1757 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001758 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 }
1760
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001761 if (restartingName != null) {
1762 // In order to let the foreground activity can be restarted with its saved state from
1763 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1764 // until the activity reports stopped with the state. And the activity record will be
1765 // kept because the record state is restarting, then the activity will be restarted
1766 // immediately if it is still the top one.
1767 mStackSupervisor.removeRestartTimeouts(r);
1768 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1769 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001770 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771
1772 Binder.restoreCallingIdentity(origId);
1773 }
1774
1775 @Override
1776 public final void activityDestroyed(IBinder token) {
1777 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1778 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001779 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001780 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001781 try {
1782 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1783 if (activity != null) {
1784 activity.destroyed("activityDestroyed");
1785 }
1786 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001787 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001788 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 }
1790 }
1791 }
1792
1793 @Override
1794 public final void activityRelaunched(IBinder token) {
1795 final long origId = Binder.clearCallingIdentity();
1796 synchronized (mGlobalLock) {
1797 mStackSupervisor.activityRelaunchedLocked(token);
1798 }
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801
1802 public final void activitySlept(IBinder token) {
1803 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1804
1805 final long origId = Binder.clearCallingIdentity();
1806
1807 synchronized (mGlobalLock) {
1808 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1809 if (r != null) {
1810 mStackSupervisor.activitySleptLocked(r);
1811 }
1812 }
1813
1814 Binder.restoreCallingIdentity(origId);
1815 }
1816
1817 @Override
1818 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1819 synchronized (mGlobalLock) {
1820 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r == null) {
1822 return;
1823 }
1824 final long origId = Binder.clearCallingIdentity();
1825 try {
1826 r.setRequestedOrientation(requestedOrientation);
1827 } finally {
1828 Binder.restoreCallingIdentity(origId);
1829 }
1830 }
1831 }
1832
1833 @Override
1834 public int getRequestedOrientation(IBinder token) {
1835 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001836 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1837 return (r != null)
1838 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 }
1840 }
1841
1842 @Override
1843 public void setImmersive(IBinder token, boolean immersive) {
1844 synchronized (mGlobalLock) {
1845 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1846 if (r == null) {
1847 throw new IllegalArgumentException();
1848 }
1849 r.immersive = immersive;
1850
1851 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001852 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001854 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 }
1856 }
1857 }
1858
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 void applyUpdateLockStateLocked(ActivityRecord r) {
1860 // Modifications to the UpdateLock state are done on our handler, outside
1861 // the activity manager's locks. The new state is determined based on the
1862 // state *now* of the relevant activity record. The object is passed to
1863 // the handler solely for logging detail, not to be consulted/modified.
1864 final boolean nextState = r != null && r.immersive;
1865 mH.post(() -> {
1866 if (mUpdateLock.isHeld() != nextState) {
1867 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1868 "Applying new update lock state '" + nextState + "' for " + r);
1869 if (nextState) {
1870 mUpdateLock.acquire();
1871 } else {
1872 mUpdateLock.release();
1873 }
1874 }
1875 });
1876 }
1877
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 @Override
1879 public boolean isImmersive(IBinder token) {
1880 synchronized (mGlobalLock) {
1881 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1882 if (r == null) {
1883 throw new IllegalArgumentException();
1884 }
1885 return r.immersive;
1886 }
1887 }
1888
1889 @Override
1890 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001893 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 return (r != null) ? r.immersive : false;
1895 }
1896 }
1897
1898 @Override
1899 public void overridePendingTransition(IBinder token, String packageName,
1900 int enterAnim, int exitAnim) {
1901 synchronized (mGlobalLock) {
1902 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1903 if (self == null) {
1904 return;
1905 }
1906
1907 final long origId = Binder.clearCallingIdentity();
1908
1909 if (self.isState(
1910 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001911 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001912 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914
1915 Binder.restoreCallingIdentity(origId);
1916 }
1917 }
1918
1919 @Override
1920 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001921 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001923 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001924 if (r == null) {
1925 return ActivityManager.COMPAT_MODE_UNKNOWN;
1926 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001927 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930
1931 @Override
1932 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001933 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001935 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001937 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001938 if (r == null) {
1939 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1940 return;
1941 }
1942 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001943 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 }
1945 }
1946
1947 @Override
1948 public int getLaunchedFromUid(IBinder activityToken) {
1949 ActivityRecord srec;
1950 synchronized (mGlobalLock) {
1951 srec = ActivityRecord.forTokenLocked(activityToken);
1952 }
1953 if (srec == null) {
1954 return -1;
1955 }
1956 return srec.launchedFromUid;
1957 }
1958
1959 @Override
1960 public String getLaunchedFromPackage(IBinder activityToken) {
1961 ActivityRecord srec;
1962 synchronized (mGlobalLock) {
1963 srec = ActivityRecord.forTokenLocked(activityToken);
1964 }
1965 if (srec == null) {
1966 return null;
1967 }
1968 return srec.launchedFromPackage;
1969 }
1970
1971 @Override
1972 public boolean convertFromTranslucent(IBinder token) {
1973 final long origId = Binder.clearCallingIdentity();
1974 try {
1975 synchronized (mGlobalLock) {
1976 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1977 if (r == null) {
1978 return false;
1979 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001980 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 }
1982 } finally {
1983 Binder.restoreCallingIdentity(origId);
1984 }
1985 }
1986
1987 @Override
1988 public boolean convertToTranslucent(IBinder token, Bundle options) {
1989 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1990 final long origId = Binder.clearCallingIdentity();
1991 try {
1992 synchronized (mGlobalLock) {
1993 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1994 if (r == null) {
1995 return false;
1996 }
Louis Changcdec0802019-11-11 11:45:07 +08001997 final Task task = r.getTask();
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001998 int index = task.mChildren.lastIndexOf(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002000 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2002 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002003 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002004 }
2005 } finally {
2006 Binder.restoreCallingIdentity(origId);
2007 }
2008 }
2009
2010 @Override
2011 public void notifyActivityDrawn(IBinder token) {
2012 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002016 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 }
2018 }
2019 }
2020
2021 @Override
2022 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2023 synchronized (mGlobalLock) {
2024 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2025 if (r == null) {
2026 return;
2027 }
2028 r.reportFullyDrawnLocked(restoredFromBundle);
2029 }
2030 }
2031
2032 @Override
2033 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2034 synchronized (mGlobalLock) {
2035 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2036 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2037 return stack.mDisplayId;
2038 }
2039 return DEFAULT_DISPLAY;
2040 }
2041 }
2042
2043 @Override
2044 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 long ident = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002049 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 return null;
2054 }
2055 } finally {
2056 Binder.restoreCallingIdentity(ident);
2057 }
2058 }
2059
2060 @Override
2061 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2064 final long callingId = Binder.clearCallingIdentity();
2065 try {
2066 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002067 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (stack == null) {
2069 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2070 return;
2071 }
2072 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002073 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002074 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(callingId);
2079 }
2080 }
2081
2082 @Override
2083 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002089 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002090 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (task == null) {
2092 return;
2093 }
2094 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002095 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002096 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 }
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(callingId);
2101 }
2102 }
2103
2104 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002105 public void restartActivityProcessIfVisible(IBinder activityToken) {
2106 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2107 final long callingId = Binder.clearCallingIdentity();
2108 try {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2111 if (r == null) {
2112 return;
2113 }
2114 r.restartProcessIfVisible();
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(callingId);
2118 }
2119 }
2120
2121 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
2127 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2128 "remove-task");
2129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
2132 }
2133 }
2134
2135 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002136 public void removeAllVisibleRecentTasks() {
2137 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2138 synchronized (mGlobalLock) {
2139 final long ident = Binder.clearCallingIdentity();
2140 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002141 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002142 } finally {
2143 Binder.restoreCallingIdentity(ident);
2144 }
2145 }
2146 }
2147
2148 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2150 synchronized (mGlobalLock) {
2151 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2152 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002153 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 }
2155 }
2156 return false;
2157 }
2158
2159 @Override
2160 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2161 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002162
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002163 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2165 if (r != null) {
2166 return r.getActivityStack().navigateUpToLocked(
2167 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172
2173 /**
2174 * Attempts to move a task backwards in z-order (the order of activities within the task is
2175 * unchanged).
2176 *
2177 * There are several possible results of this call:
2178 * - if the task is locked, then we will show the lock toast
2179 * - if there is a task behind the provided task, then that task is made visible and resumed as
2180 * this task is moved to the back
2181 * - otherwise, if there are no other tasks in the stack:
2182 * - if this task is in the pinned stack, then we remove the stack completely, which will
2183 * have the effect of moving the task to the top or bottom of the fullscreen stack
2184 * (depending on whether it is visible)
2185 * - otherwise, we simply return home and hide this task
2186 *
2187 * @param token A reference to the activity we wish to move
2188 * @param nonRoot If false then this only works if the activity is the root
2189 * of a task; if true it will work for any activity in a task.
2190 * @return Returns true if the move completed, false if not.
2191 */
2192 @Override
2193 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
2198 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002199 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task != null) {
2201 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2202 }
2203 } finally {
2204 Binder.restoreCallingIdentity(origId);
2205 }
2206 }
2207 return false;
2208 }
2209
2210 @Override
2211 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 long ident = Binder.clearCallingIdentity();
2214 Rect rect = new Rect();
2215 try {
2216 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002217 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2219 if (task == null) {
2220 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2221 return rect;
2222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002223 if (task.getParent() != null) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(ident);
2231 }
2232 return rect;
2233 }
2234
2235 @Override
2236 public ActivityManager.TaskDescription getTaskDescription(int id) {
2237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002238 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002240 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2242 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002243 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245 }
2246 return null;
2247 }
2248
2249 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002250 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2251 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2252 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2253 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2254 return;
2255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 synchronized (mGlobalLock) {
2258 final long ident = Binder.clearCallingIdentity();
2259 try {
Louis Changcdec0802019-11-11 11:45:07 +08002260 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002261 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 if (task == null) {
2263 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2264 return;
2265 }
2266
2267 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2268 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2269
2270 if (!task.isActivityTypeStandardOrUndefined()) {
2271 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2272 + " non-standard task " + taskId + " to windowing mode="
2273 + windowingMode);
2274 }
2275
2276 final ActivityStack stack = task.getStack();
2277 if (toTop) {
2278 stack.moveToFront("setTaskWindowingMode", task);
2279 }
2280 stack.setWindowingMode(windowingMode);
2281 } finally {
2282 Binder.restoreCallingIdentity(ident);
2283 }
2284 }
2285 }
2286
2287 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 ActivityRecord r = getCallingRecordLocked(token);
2291 return r != null ? r.info.packageName : null;
2292 }
2293 }
2294
2295 @Override
2296 public ComponentName getCallingActivity(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.intent.getComponent() : null;
2300 }
2301 }
2302
2303 private ActivityRecord getCallingRecordLocked(IBinder token) {
2304 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2305 if (r == null) {
2306 return null;
2307 }
2308 return r.resultTo;
2309 }
2310
2311 @Override
2312 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002313 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314
2315 synchronized (mGlobalLock) {
2316 final long origId = Binder.clearCallingIdentity();
2317 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002318 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 } finally {
2320 Binder.restoreCallingIdentity(origId);
2321 }
2322 }
2323 }
2324
Mark Renouf446251d2019-04-26 10:22:41 -04002325 @Override
2326 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2327 synchronized (mGlobalLock) {
2328 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2329 if (r == null) {
2330 return;
2331 }
2332 ActivityStack stack = r.getActivityStack();
2333 if (stack != null && stack.isSingleTaskInstance()) {
2334 // Single-task stacks are used for activities which are presented in floating
2335 // windows above full screen activities. Instead of directly finishing the
2336 // task, a task change listener is used to notify SystemUI so the action can be
2337 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002338 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002339 mTaskChangeNotificationController
2340 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2341 } else {
2342 try {
2343 callback.requestFinish();
2344 } catch (RemoteException e) {
2345 Slog.e(TAG, "Failed to invoke request finish callback", e);
2346 }
2347 }
2348 }
2349 }
2350
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 /**
2352 * TODO: Add mController hook
2353 */
2354 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2356 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358
2359 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2360 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002361 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2362 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363 }
2364 }
2365
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2367 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002369
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 final int callingPid = Binder.getCallingPid();
2371 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002372 if (!isSameApp(callingUid, callingPackage)) {
2373 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2374 + Binder.getCallingPid() + " as package " + callingPackage;
2375 Slog.w(TAG, msg);
2376 throw new SecurityException(msg);
2377 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379 SafeActivityOptions.abort(options);
2380 return;
2381 }
2382 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 WindowProcessController callerApp = null;
2384 if (appThread != null) {
2385 callerApp = getProcessController(appThread);
2386 }
2387 final ActivityStarter starter = getActivityStartController().obtainStarter(
2388 null /* intent */, "moveTaskToFront");
2389 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2390 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002391 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 return;
2393 }
2394 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 try {
Louis Changcdec0802019-11-11 11:45:07 +08002396 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 if (task == null) {
2398 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002399 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 return;
2401 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002402 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002404 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 return;
2406 }
2407 ActivityOptions realOptions = options != null
2408 ? options.getOptions(mStackSupervisor)
2409 : null;
2410 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2411 false /* forceNonResizable */);
2412
Wale Ogunwale21e06482019-11-18 05:14:15 -08002413 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 if (topActivity != null) {
2415
2416 // We are reshowing a task, use a starting window to hide the initial draw delay
2417 // so the transition can start earlier.
2418 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2419 true /* taskSwitch */, fromRecents);
2420 }
2421 } finally {
2422 Binder.restoreCallingIdentity(origId);
2423 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 }
2425
Ricky Waiaca8a772019-04-04 16:01:06 +01002426 /**
2427 * Return true if callingUid is system, or packageName belongs to that callingUid.
2428 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002429 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002430 try {
2431 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2432 if (packageName == null) {
2433 return false;
2434 }
2435 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2436 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2437 UserHandle.getUserId(callingUid));
2438 return UserHandle.isSameApp(callingUid, uid);
2439 }
2440 } catch (RemoteException e) {
2441 // Should not happen
2442 }
2443 return true;
2444 }
2445
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002446 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2447 int callingPid, int callingUid, String name) {
2448 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2449 return true;
2450 }
2451
2452 if (getRecentTasks().isCallerRecents(sourceUid)) {
2453 return true;
2454 }
2455
2456 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2457 if (perm == PackageManager.PERMISSION_GRANTED) {
2458 return true;
2459 }
2460 if (checkAllowAppSwitchUid(sourceUid)) {
2461 return true;
2462 }
2463
2464 // If the actual IPC caller is different from the logical source, then
2465 // also see if they are allowed to control app switches.
2466 if (callingUid != -1 && callingUid != sourceUid) {
2467 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2468 if (perm == PackageManager.PERMISSION_GRANTED) {
2469 return true;
2470 }
2471 if (checkAllowAppSwitchUid(callingUid)) {
2472 return true;
2473 }
2474 }
2475
2476 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2477 return false;
2478 }
2479
2480 private boolean checkAllowAppSwitchUid(int uid) {
2481 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2482 if (types != null) {
2483 for (int i = types.size() - 1; i >= 0; i--) {
2484 if (types.valueAt(i).intValue() == uid) {
2485 return true;
2486 }
2487 }
2488 }
2489 return false;
2490 }
2491
2492 @Override
2493 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2494 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2495 "setActivityController()");
2496 synchronized (mGlobalLock) {
2497 mController = controller;
2498 mControllerIsAMonkey = imAMonkey;
2499 Watchdog.getInstance().setActivityController(controller);
2500 }
2501 }
2502
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002503 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 synchronized (mGlobalLock) {
2505 return mController != null && mControllerIsAMonkey;
2506 }
2507 }
2508
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 @Override
2510 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2511 synchronized (mGlobalLock) {
2512 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2513 }
2514 }
2515
2516 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2518 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2519 }
2520
2521 @Override
2522 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2523 @WindowConfiguration.ActivityType int ignoreActivityType,
2524 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2525 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002526 final int callingPid = Binder.getCallingPid();
2527 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002528 final int[] profileIds = getUserManager().getProfileIds(
2529 UserHandle.getUserId(callingUid), true);
2530 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2531 for (int i = 0; i < profileIds.length; i++) {
2532 callingProfileIds.add(profileIds[i]);
2533 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002534 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2535
2536 synchronized (mGlobalLock) {
2537 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2538
Nicholas Sauer0259e532019-08-30 08:24:55 -07002539 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002540 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002541 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 }
2543
2544 return list;
2545 }
2546
2547 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2549 synchronized (mGlobalLock) {
2550 final long origId = Binder.clearCallingIdentity();
2551 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2552 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002553 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 }
2555 Binder.restoreCallingIdentity(origId);
2556 }
2557 }
2558
2559 @Override
2560 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 ActivityStack stack = ActivityRecord.getStackLocked(token);
2563 if (stack != null) {
2564 return stack.willActivityBeVisibleLocked(token);
2565 }
2566 return false;
2567 }
2568 }
2569
2570 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 synchronized (mGlobalLock) {
2574 final long ident = Binder.clearCallingIdentity();
2575 try {
Louis Changcdec0802019-11-11 11:45:07 +08002576 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 if (task == null) {
2578 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2579 return;
2580 }
2581
2582 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2583 + " to stackId=" + stackId + " toTop=" + toTop);
2584
Wale Ogunwaled32da472018-11-16 07:19:28 -08002585 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 if (stack == null) {
2587 throw new IllegalStateException(
2588 "moveTaskToStack: No stack for stackId=" + stackId);
2589 }
2590 if (!stack.isActivityTypeStandardOrUndefined()) {
2591 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2592 + taskId + " to stack " + stackId);
2593 }
2594 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002595 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2597 }
2598 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2599 "moveTaskToStack");
2600 } finally {
2601 Binder.restoreCallingIdentity(ident);
2602 }
2603 }
2604 }
2605
2606 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002607 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2608 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609
2610 final long ident = Binder.clearCallingIdentity();
2611 try {
2612 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002613 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2614 if (stack == null) {
2615 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2616 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002618 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2619 throw new IllegalArgumentException("Stack: " + stackId
2620 + " doesn't support animated resize.");
2621 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002622 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002623 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 }
2625 } finally {
2626 Binder.restoreCallingIdentity(ident);
2627 }
2628 }
2629
wilsonshih5c4cf522019-01-25 09:03:47 +08002630 @Override
2631 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2632 int animationDuration) {
2633 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2634
2635 final long ident = Binder.clearCallingIdentity();
2636 try {
2637 synchronized (mGlobalLock) {
2638 if (xOffset == 0 && yOffset == 0) {
2639 return;
2640 }
2641 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2642 if (stack == null) {
2643 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2644 return;
2645 }
2646 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2647 throw new IllegalArgumentException("Stack: " + stackId
2648 + " doesn't support animated resize.");
2649 }
2650 final Rect destBounds = new Rect();
2651 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002652 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002653 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2654 return;
2655 }
2656 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002657 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002658 animationDuration, false /* fromFullscreen */);
2659 }
2660 } finally {
2661 Binder.restoreCallingIdentity(ident);
2662 }
2663 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 /**
2665 * Moves the specified task to the primary-split-screen stack.
2666 *
2667 * @param taskId Id of task to move.
2668 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2669 * exist already. See
2670 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2671 * and
2672 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2673 * @param toTop If the task and stack should be moved to the top.
2674 * @param animate Whether we should play an animation for the moving the task.
2675 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2676 * stack. Pass {@code null} to use default bounds.
2677 * @param showRecents If the recents activity should be shown on the other side of the task
2678 * going into split-screen mode.
2679 */
2680 @Override
2681 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2682 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002683 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 "setTaskWindowingModeSplitScreenPrimary()");
2685 synchronized (mGlobalLock) {
2686 final long ident = Binder.clearCallingIdentity();
2687 try {
Louis Changcdec0802019-11-11 11:45:07 +08002688 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002689 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 if (task == null) {
2691 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2692 return false;
2693 }
2694 if (DEBUG_STACK) Slog.d(TAG_STACK,
2695 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2696 + " to createMode=" + createMode + " toTop=" + toTop);
2697 if (!task.isActivityTypeStandardOrUndefined()) {
2698 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2699 + " non-standard task " + taskId + " to split-screen windowing mode");
2700 }
2701
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002702 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 final int windowingMode = task.getWindowingMode();
2704 final ActivityStack stack = task.getStack();
2705 if (toTop) {
2706 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2707 }
2708 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002709 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2710 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 return windowingMode != task.getWindowingMode();
2712 } finally {
2713 Binder.restoreCallingIdentity(ident);
2714 }
2715 }
2716 }
2717
2718 /**
2719 * Removes stacks in the input windowing modes from the system if they are of activity type
2720 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2721 */
2722 @Override
2723 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002724 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 "removeStacksInWindowingModes()");
2726
2727 synchronized (mGlobalLock) {
2728 final long ident = Binder.clearCallingIdentity();
2729 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002730 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 } finally {
2732 Binder.restoreCallingIdentity(ident);
2733 }
2734 }
2735 }
2736
2737 @Override
2738 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002739 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 "removeStacksWithActivityTypes()");
2741
2742 synchronized (mGlobalLock) {
2743 final long ident = Binder.clearCallingIdentity();
2744 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002745 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 } finally {
2747 Binder.restoreCallingIdentity(ident);
2748 }
2749 }
2750 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751
2752 @Override
2753 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2754 int userId) {
2755 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2757 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 final boolean detailed = checkGetTasksPermission(
2760 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2761 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 == PackageManager.PERMISSION_GRANTED;
2763
2764 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002765 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 callingUid);
2767 }
2768 }
2769
2770 @Override
2771 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 long ident = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002776 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 }
2778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782
2783 @Override
2784 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002785 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 long ident = Binder.clearCallingIdentity();
2787 try {
2788 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002789 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 }
2791 } finally {
2792 Binder.restoreCallingIdentity(ident);
2793 }
2794 }
2795
2796 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002797 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2798 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2799 long ident = Binder.clearCallingIdentity();
2800 try {
2801 synchronized (mGlobalLock) {
2802 return mRootActivityContainer.getAllStackInfos(displayId);
2803 }
2804 } finally {
2805 Binder.restoreCallingIdentity(ident);
2806 }
2807 }
2808
2809 @Override
2810 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2811 int displayId) {
2812 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2813 long ident = Binder.clearCallingIdentity();
2814 try {
2815 synchronized (mGlobalLock) {
2816 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2817 }
2818 } finally {
2819 Binder.restoreCallingIdentity(ident);
2820 }
2821 }
2822
2823 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002825 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 final long callingUid = Binder.getCallingUid();
2827 final long origId = Binder.clearCallingIdentity();
2828 try {
2829 synchronized (mGlobalLock) {
2830 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002831 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002832 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2833 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2834 }
2835 } finally {
2836 Binder.restoreCallingIdentity(origId);
2837 }
2838 }
2839
2840 @Override
2841 public void startLockTaskModeByToken(IBinder token) {
2842 synchronized (mGlobalLock) {
2843 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2844 if (r == null) {
2845 return;
2846 }
Louis Changcdec0802019-11-11 11:45:07 +08002847 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 }
2849 }
2850
2851 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002852 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 // This makes inner call to look as if it was initiated by system.
2855 long ident = Binder.clearCallingIdentity();
2856 try {
2857 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002858 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002859 MATCH_TASK_IN_STACKS_ONLY);
2860 if (task == null) {
2861 return;
2862 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002863
2864 // When starting lock task mode the stack must be in front and focused
2865 task.getStack().moveToFront("startSystemLockTaskMode");
2866 startLockTaskModeLocked(task, true /* isSystemCaller */);
2867 }
2868 } finally {
2869 Binder.restoreCallingIdentity(ident);
2870 }
2871 }
2872
2873 @Override
2874 public void stopLockTaskModeByToken(IBinder token) {
2875 synchronized (mGlobalLock) {
2876 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2877 if (r == null) {
2878 return;
2879 }
Louis Changcdec0802019-11-11 11:45:07 +08002880 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 }
2882 }
2883
2884 /**
2885 * This API should be called by SystemUI only when user perform certain action to dismiss
2886 * lock task mode. We should only dismiss pinned lock task mode in this case.
2887 */
2888 @Override
2889 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002890 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2892 }
2893
Louis Changcdec0802019-11-11 11:45:07 +08002894 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2896 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2897 return;
2898 }
2899
Wale Ogunwaled32da472018-11-16 07:19:28 -08002900 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 if (stack == null || task != stack.topTask()) {
2902 throw new IllegalArgumentException("Invalid task, not in foreground");
2903 }
2904
2905 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2906 // system or a specific app.
2907 // * System-initiated requests will only start the pinned mode (screen pinning)
2908 // * App-initiated requests
2909 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2910 // - will start the pinned mode, otherwise
2911 final int callingUid = Binder.getCallingUid();
2912 long ident = Binder.clearCallingIdentity();
2913 try {
2914 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002915 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002917 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
Louis Changcdec0802019-11-11 11:45:07 +08002923 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 final int callingUid = Binder.getCallingUid();
2925 long ident = Binder.clearCallingIdentity();
2926 try {
2927 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002928 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 }
2930 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2931 // task and jumping straight into a call in the case of emergency call back.
2932 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2933 if (tm != null) {
2934 tm.showInCallScreen(false);
2935 }
2936 } finally {
2937 Binder.restoreCallingIdentity(ident);
2938 }
2939 }
2940
2941 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002942 public void updateLockTaskPackages(int userId, String[] packages) {
2943 final int callingUid = Binder.getCallingUid();
2944 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2945 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2946 "updateLockTaskPackages()");
2947 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002948 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002949 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2950 + Arrays.toString(packages));
2951 getLockTaskController().updateLockTaskPackages(userId, packages);
2952 }
2953 }
2954
2955 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 public boolean isInLockTaskMode() {
2957 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2958 }
2959
2960 @Override
2961 public int getLockTaskModeState() {
2962 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002963 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 }
2965 }
2966
2967 @Override
2968 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2969 synchronized (mGlobalLock) {
2970 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2971 if (r != null) {
2972 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002973 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002975 }
2976 }
2977 }
2978
2979 @Override
2980 public Bundle getActivityOptions(IBinder token) {
2981 final long origId = Binder.clearCallingIdentity();
2982 try {
2983 synchronized (mGlobalLock) {
2984 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2985 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002986 final ActivityOptions activityOptions = r.takeOptionsLocked(
2987 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 return activityOptions == null ? null : activityOptions.toBundle();
2989 }
2990 return null;
2991 }
2992 } finally {
2993 Binder.restoreCallingIdentity(origId);
2994 }
2995 }
2996
2997 @Override
2998 public List<IBinder> getAppTasks(String callingPackage) {
2999 int callingUid = Binder.getCallingUid();
3000 long ident = Binder.clearCallingIdentity();
3001 try {
3002 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003003 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005 } finally {
3006 Binder.restoreCallingIdentity(ident);
3007 }
3008 }
3009
3010 @Override
3011 public void finishVoiceTask(IVoiceInteractionSession session) {
3012 synchronized (mGlobalLock) {
3013 final long origId = Binder.clearCallingIdentity();
3014 try {
3015 // TODO: VI Consider treating local voice interactions and voice tasks
3016 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003017 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 } finally {
3019 Binder.restoreCallingIdentity(origId);
3020 }
3021 }
3022
3023 }
3024
3025 @Override
3026 public boolean isTopOfTask(IBinder token) {
3027 synchronized (mGlobalLock) {
3028 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003029 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 }
3031 }
3032
3033 @Override
3034 public void notifyLaunchTaskBehindComplete(IBinder token) {
3035 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3036 }
3037
3038 @Override
3039 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003040 mH.post(() -> {
3041 synchronized (mGlobalLock) {
3042 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003043 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003044 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003045 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003046 } catch (RemoteException e) {
3047 }
3048 }
3049 }
3050
3051 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 }
3053
3054 /** Called from an app when assist data is ready. */
3055 @Override
3056 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3057 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003058 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 synchronized (pae) {
3060 pae.result = extras;
3061 pae.structure = structure;
3062 pae.content = content;
3063 if (referrer != null) {
3064 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3065 }
3066 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003067 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003068 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003069 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 structure.setHomeActivity(pae.isHome);
3071 }
3072 pae.haveResult = true;
3073 pae.notifyAll();
3074 if (pae.intent == null && pae.receiver == null) {
3075 // Caller is just waiting for the result.
3076 return;
3077 }
3078 }
3079 // We are now ready to launch the assist activity.
3080 IAssistDataReceiver sendReceiver = null;
3081 Bundle sendBundle = null;
3082 synchronized (mGlobalLock) {
3083 buildAssistBundleLocked(pae, extras);
3084 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003085 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086 if (!exists) {
3087 // Timed out.
3088 return;
3089 }
3090
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003091 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 // Caller wants result sent back to them.
3093 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003094 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003095 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003096 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3097 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3099 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3100 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3101 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3102 }
3103 }
3104 if (sendReceiver != null) {
3105 try {
3106 sendReceiver.onHandleAssistData(sendBundle);
3107 } catch (RemoteException e) {
3108 }
3109 return;
3110 }
3111
3112 final long ident = Binder.clearCallingIdentity();
3113 try {
3114 if (TextUtils.equals(pae.intent.getAction(),
3115 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003116 // Start voice interaction through VoiceInteractionManagerService.
3117 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3118 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 } else {
3120 pae.intent.replaceExtras(pae.extras);
3121 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3122 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3123 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003124 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125
3126 try {
3127 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3128 } catch (ActivityNotFoundException e) {
3129 Slog.w(TAG, "No activity to handle assist action.", e);
3130 }
3131 }
3132 } finally {
3133 Binder.restoreCallingIdentity(ident);
3134 }
3135 }
3136
3137 @Override
3138 public int addAppTask(IBinder activityToken, Intent intent,
3139 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3140 final int callingUid = Binder.getCallingUid();
3141 final long callingIdent = Binder.clearCallingIdentity();
3142
3143 try {
3144 synchronized (mGlobalLock) {
3145 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3146 if (r == null) {
3147 throw new IllegalArgumentException("Activity does not exist; token="
3148 + activityToken);
3149 }
3150 ComponentName comp = intent.getComponent();
3151 if (comp == null) {
3152 throw new IllegalArgumentException("Intent " + intent
3153 + " must specify explicit component");
3154 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003155 if (thumbnail.getWidth() != mThumbnailWidth
3156 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 throw new IllegalArgumentException("Bad thumbnail size: got "
3158 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003159 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 }
3161 if (intent.getSelector() != null) {
3162 intent.setSelector(null);
3163 }
3164 if (intent.getSourceBounds() != null) {
3165 intent.setSourceBounds(null);
3166 }
3167 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3168 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3169 // The caller has added this as an auto-remove task... that makes no
3170 // sense, so turn off auto-remove.
3171 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3172 }
3173 }
3174 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3175 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3176 if (ainfo.applicationInfo.uid != callingUid) {
3177 throw new SecurityException(
3178 "Can't add task for another application: target uid="
3179 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3180 }
3181
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003182 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003183 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003184 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003186 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003188 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 return INVALID_TASK_ID;
3190 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003191 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192
3193 // TODO: Send the thumbnail to WM to store it.
3194
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003195 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 } finally {
3198 Binder.restoreCallingIdentity(callingIdent);
3199 }
3200 }
3201
3202 @Override
3203 public Point getAppTaskThumbnailSize() {
3204 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003205 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 }
3207 }
3208
3209 @Override
3210 public void setTaskResizeable(int taskId, int resizeableMode) {
3211 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003212 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3214 if (task == null) {
3215 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3216 return;
3217 }
3218 task.setResizeMode(resizeableMode);
3219 }
3220 }
3221
3222 @Override
3223 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003224 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 long ident = Binder.clearCallingIdentity();
3226 try {
3227 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003228 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003229 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 if (task == null) {
3231 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3232 return;
3233 }
3234 // Place the task in the right stack if it isn't there already based on
3235 // the requested bounds.
3236 // The stack transition logic is:
3237 // - a null bounds on a freeform task moves that task to fullscreen
3238 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3239 // that task to freeform
3240 // - otherwise the task is not moved
3241 ActivityStack stack = task.getStack();
3242 if (!task.getWindowConfiguration().canResizeTask()) {
3243 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3244 }
3245 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3246 stack = stack.getDisplay().getOrCreateStack(
3247 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3248 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3249 stack = stack.getDisplay().getOrCreateStack(
3250 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3251 }
3252
3253 // Reparent the task to the right stack if necessary
3254 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3255 if (stack != task.getStack()) {
3256 // Defer resume until the task is resized below
3257 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3258 DEFER_RESUME, "resizeTask");
3259 preserveWindow = false;
3260 }
3261
3262 // After reparenting (which only resizes the task to the stack bounds), resize the
3263 // task to the actual bounds provided
3264 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3265 }
3266 } finally {
3267 Binder.restoreCallingIdentity(ident);
3268 }
3269 }
3270
Evan Roskyddedfd42019-10-04 13:38:38 -07003271 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3272 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003273 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003274 throw new RuntimeException("Invalid token in task transaction");
3275 }
3276 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3277 // masks here.
3278 int configMask = change.getConfigSetMask();
3279 int windowMask = change.getWindowSetMask();
3280 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3281 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3282 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3283 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3284 c.setTo(change.getConfiguration(), configMask, windowMask);
3285 container.onRequestedOverrideConfigurationChanged(c);
3286 }
3287
3288 @Override
3289 public void applyContainerTransaction(WindowContainerTransaction t) {
3290 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3291 long ident = Binder.clearCallingIdentity();
3292 try {
3293 if (t == null) {
3294 return;
3295 }
3296 synchronized (mGlobalLock) {
3297 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3298 t.getChanges().entrySet().iterator();
3299 while (entries.hasNext()) {
3300 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3301 entries.next();
3302 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3303 entry.getKey()).getContainer();
3304 sanitizeAndApplyConfigChange(cc, entry.getValue());
3305 }
3306 }
3307 } finally {
3308 Binder.restoreCallingIdentity(ident);
3309 }
3310 }
3311
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 @Override
3313 public boolean releaseActivityInstance(IBinder token) {
3314 synchronized (mGlobalLock) {
3315 final long origId = Binder.clearCallingIdentity();
3316 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003317 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3318 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 return false;
3320 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003321 r.destroyImmediately(true /* removeFromApp */, "app-req");
3322 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 } finally {
3324 Binder.restoreCallingIdentity(origId);
3325 }
3326 }
3327 }
3328
3329 @Override
3330 public void releaseSomeActivities(IApplicationThread appInt) {
3331 synchronized (mGlobalLock) {
3332 final long origId = Binder.clearCallingIdentity();
3333 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003334 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003335 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 } finally {
3337 Binder.restoreCallingIdentity(origId);
3338 }
3339 }
3340 }
3341
3342 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003343 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003344 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 != PackageManager.PERMISSION_GRANTED) {
3346 throw new SecurityException("Requires permission "
3347 + android.Manifest.permission.DEVICE_POWER);
3348 }
3349
3350 synchronized (mGlobalLock) {
3351 long ident = Binder.clearCallingIdentity();
3352 if (mKeyguardShown != keyguardShowing) {
3353 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003354 final Message msg = PooledLambda.obtainMessage(
3355 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3356 keyguardShowing);
3357 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 }
3359 try {
wilsonshih177261f2019-02-22 12:02:18 +08003360 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(ident);
3363 }
3364 }
3365
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003366 mH.post(() -> {
3367 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3368 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3369 }
3370 });
3371 }
3372
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003373 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003374 mH.post(() -> {
3375 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3376 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3377 }
3378 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 }
3380
3381 @Override
3382 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003383 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3384 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385
3386 final File passedIconFile = new File(filePath);
3387 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3388 passedIconFile.getName());
3389 if (!legitIconFile.getPath().equals(filePath)
3390 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3391 throw new IllegalArgumentException("Bad file path: " + filePath
3392 + " passed for userId " + userId);
3393 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003394 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 }
3396
3397 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 synchronized (mGlobalLock) {
3401 final long ident = Binder.clearCallingIdentity();
3402 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003403 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 if (stack == null) {
3405 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3406 return;
3407 }
3408 if (!stack.isActivityTypeStandardOrUndefined()) {
3409 throw new IllegalArgumentException(
3410 "Removing non-standard stack is not allowed.");
3411 }
3412 mStackSupervisor.removeStack(stack);
3413 } finally {
3414 Binder.restoreCallingIdentity(ident);
3415 }
3416 }
3417 }
3418
3419 @Override
3420 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422
3423 synchronized (mGlobalLock) {
3424 final long ident = Binder.clearCallingIdentity();
3425 try {
3426 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3427 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003428 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433 }
3434
3435 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003436 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 synchronized (mGlobalLock) {
3438 long ident = Binder.clearCallingIdentity();
3439 try {
3440 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3441 if (r == null) {
3442 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003443 "toggleFreeformWindowingMode: No activity record matching token="
3444 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 }
3446
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003447 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003448 if (stack == null) {
3449 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3450 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003451 }
3452
Yunfan Chend967af82019-01-17 18:30:18 +09003453 if (!stack.inFreeformWindowingMode()
3454 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3455 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3456 + "toggle between fullscreen and freeform.");
3457 }
3458
3459 if (stack.inFreeformWindowingMode()) {
3460 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003461 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003462 throw new IllegalStateException("Size-compat windows are currently not"
3463 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003464 } else if (stack.getParent().inFreeformWindowingMode()) {
3465 // If the window is on a freeform display, set it to undefined. It will be
3466 // resolved to freeform and it can adjust windowing mode when the display mode
3467 // changes in runtime.
3468 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003469 } else {
3470 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3471 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 } finally {
3473 Binder.restoreCallingIdentity(ident);
3474 }
3475 }
3476 }
3477
3478 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3479 @Override
3480 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003483 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
3486 /** Unregister a task stack listener so that it stops receiving callbacks. */
3487 @Override
3488 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003489 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003491 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492 }
3493
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003494 @Override
3495 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3496 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3497 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3498 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3499 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3500 }
3501
3502 @Override
3503 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3504 IBinder activityToken, int flags) {
3505 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3506 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3507 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3508 }
3509
3510 @Override
3511 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3512 Bundle args) {
3513 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3514 true /* focused */, true /* newSessionId */, userHandle, args,
3515 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3516 }
3517
3518 @Override
3519 public Bundle getAssistContextExtras(int requestType) {
3520 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3521 null, null, true /* focused */, true /* newSessionId */,
3522 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3523 if (pae == null) {
3524 return null;
3525 }
3526 synchronized (pae) {
3527 while (!pae.haveResult) {
3528 try {
3529 pae.wait();
3530 } catch (InterruptedException e) {
3531 }
3532 }
3533 }
3534 synchronized (mGlobalLock) {
3535 buildAssistBundleLocked(pae, pae.result);
3536 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003537 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 }
3539 return pae.extras;
3540 }
3541
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003542 /**
3543 * Binder IPC calls go through the public entry point.
3544 * This can be called with or without the global lock held.
3545 */
3546 private static int checkCallingPermission(String permission) {
3547 return checkPermission(
3548 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3549 }
3550
3551 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003552 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003553 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3554 mAmInternal.enforceCallingPermission(permission, func);
3555 }
3556 }
3557
3558 @VisibleForTesting
3559 int checkGetTasksPermission(String permission, int pid, int uid) {
3560 return checkPermission(permission, pid, uid);
3561 }
3562
3563 static int checkPermission(String permission, int pid, int uid) {
3564 if (permission == null) {
3565 return PackageManager.PERMISSION_DENIED;
3566 }
3567 return checkComponentPermission(permission, pid, uid, -1, true);
3568 }
3569
Wale Ogunwale214f3482018-10-04 11:00:47 -07003570 public static int checkComponentPermission(String permission, int pid, int uid,
3571 int owningUid, boolean exported) {
3572 return ActivityManagerService.checkComponentPermission(
3573 permission, pid, uid, owningUid, exported);
3574 }
3575
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003576 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3577 if (getRecentTasks().isCallerRecents(callingUid)) {
3578 // Always allow the recents component to get tasks
3579 return true;
3580 }
3581
3582 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3583 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3584 if (!allowed) {
3585 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3586 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3587 // Temporary compatibility: some existing apps on the system image may
3588 // still be requesting the old permission and not switched to the new
3589 // one; if so, we'll still allow them full access. This means we need
3590 // to see if they are holding the old permission and are a system app.
3591 try {
3592 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3593 allowed = true;
3594 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3595 + " is using old GET_TASKS but privileged; allowing");
3596 }
3597 } catch (RemoteException e) {
3598 }
3599 }
3600 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3601 + " does not hold REAL_GET_TASKS; limiting output");
3602 }
3603 return allowed;
3604 }
3605
Nicholas Sauer0259e532019-08-30 08:24:55 -07003606 boolean isCrossUserAllowed(int pid, int uid) {
3607 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3608 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3609 }
3610
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3612 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3613 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3614 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003615 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003616 "enqueueAssistContext()");
3617
3618 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003619 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 if (activity == null) {
3621 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3622 return null;
3623 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003624 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003625 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3626 return null;
3627 }
3628 if (focused) {
3629 if (activityToken != null) {
3630 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3631 if (activity != caller) {
3632 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3633 + " is not current top " + activity);
3634 return null;
3635 }
3636 }
3637 } else {
3638 activity = ActivityRecord.forTokenLocked(activityToken);
3639 if (activity == null) {
3640 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3641 + " couldn't be found");
3642 return null;
3643 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003644 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3646 return null;
3647 }
3648 }
3649
3650 PendingAssistExtras pae;
3651 Bundle extras = new Bundle();
3652 if (args != null) {
3653 extras.putAll(args);
3654 }
3655 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003656 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003657
3658 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3659 userHandle);
3660 pae.isHome = activity.isActivityTypeHome();
3661
3662 // Increment the sessionId if necessary
3663 if (newSessionId) {
3664 mViSessionId++;
3665 }
3666 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003667 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3668 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003670 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 } catch (RemoteException e) {
3672 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3673 return null;
3674 }
3675 return pae;
3676 }
3677 }
3678
3679 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3680 if (result != null) {
3681 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3682 }
3683 if (pae.hint != null) {
3684 pae.extras.putBoolean(pae.hint, true);
3685 }
3686 }
3687
3688 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3689 IAssistDataReceiver receiver;
3690 synchronized (mGlobalLock) {
3691 mPendingAssistExtras.remove(pae);
3692 receiver = pae.receiver;
3693 }
3694 if (receiver != null) {
3695 // Caller wants result sent back to them.
3696 Bundle sendBundle = new Bundle();
3697 // At least return the receiver extras
3698 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3699 try {
3700 pae.receiver.onHandleAssistData(sendBundle);
3701 } catch (RemoteException e) {
3702 }
3703 }
3704 }
3705
3706 public class PendingAssistExtras extends Binder implements Runnable {
3707 public final ActivityRecord activity;
3708 public boolean isHome;
3709 public final Bundle extras;
3710 public final Intent intent;
3711 public final String hint;
3712 public final IAssistDataReceiver receiver;
3713 public final int userHandle;
3714 public boolean haveResult = false;
3715 public Bundle result = null;
3716 public AssistStructure structure = null;
3717 public AssistContent content = null;
3718 public Bundle receiverExtras;
3719
3720 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3721 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3722 int _userHandle) {
3723 activity = _activity;
3724 extras = _extras;
3725 intent = _intent;
3726 hint = _hint;
3727 receiver = _receiver;
3728 receiverExtras = _receiverExtras;
3729 userHandle = _userHandle;
3730 }
3731
3732 @Override
3733 public void run() {
3734 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3735 synchronized (this) {
3736 haveResult = true;
3737 notifyAll();
3738 }
3739 pendingAssistExtrasTimedOut(this);
3740 }
3741 }
3742
3743 @Override
3744 public boolean isAssistDataAllowedOnCurrentActivity() {
3745 int userId;
3746 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003747 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3749 return false;
3750 }
3751
Wale Ogunwale21e06482019-11-18 05:14:15 -08003752 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 if (activity == null) {
3754 return false;
3755 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003756 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003757 }
3758 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3759 }
3760
3761 @Override
3762 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3763 long ident = Binder.clearCallingIdentity();
3764 try {
3765 synchronized (mGlobalLock) {
3766 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003767 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (top != caller) {
3769 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3770 + " is not current top " + top);
3771 return false;
3772 }
3773 if (!top.nowVisible) {
3774 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3775 + " is not visible");
3776 return false;
3777 }
3778 }
3779 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3780 token);
3781 } finally {
3782 Binder.restoreCallingIdentity(ident);
3783 }
3784 }
3785
3786 @Override
3787 public boolean isRootVoiceInteraction(IBinder token) {
3788 synchronized (mGlobalLock) {
3789 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3790 if (r == null) {
3791 return false;
3792 }
3793 return r.rootVoiceInteraction;
3794 }
3795 }
3796
Wale Ogunwalef6733932018-06-27 05:14:34 -07003797 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3798 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3799 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3800 if (activityToCallback == null) return;
3801 activityToCallback.setVoiceSessionLocked(voiceSession);
3802
3803 // Inform the activity
3804 try {
3805 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3806 voiceInteractor);
3807 long token = Binder.clearCallingIdentity();
3808 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003809 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003810 } finally {
3811 Binder.restoreCallingIdentity(token);
3812 }
3813 // TODO: VI Should we cache the activity so that it's easier to find later
3814 // rather than scan through all the stacks and activities?
3815 } catch (RemoteException re) {
3816 activityToCallback.clearVoiceSessionLocked();
3817 // TODO: VI Should this terminate the voice session?
3818 }
3819 }
3820
3821 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3822 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3823 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3824 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3825 boolean wasRunningVoice = mRunningVoice != null;
3826 mRunningVoice = session;
3827 if (!wasRunningVoice) {
3828 mVoiceWakeLock.acquire();
3829 updateSleepIfNeededLocked();
3830 }
3831 }
3832 }
3833
3834 void finishRunningVoiceLocked() {
3835 if (mRunningVoice != null) {
3836 mRunningVoice = null;
3837 mVoiceWakeLock.release();
3838 updateSleepIfNeededLocked();
3839 }
3840 }
3841
3842 @Override
3843 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3844 synchronized (mGlobalLock) {
3845 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3846 if (keepAwake) {
3847 mVoiceWakeLock.acquire();
3848 } else {
3849 mVoiceWakeLock.release();
3850 }
3851 }
3852 }
3853 }
3854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 @Override
3856 public ComponentName getActivityClassForToken(IBinder token) {
3857 synchronized (mGlobalLock) {
3858 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3859 if (r == null) {
3860 return null;
3861 }
3862 return r.intent.getComponent();
3863 }
3864 }
3865
3866 @Override
3867 public String getPackageForToken(IBinder token) {
3868 synchronized (mGlobalLock) {
3869 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3870 if (r == null) {
3871 return null;
3872 }
3873 return r.packageName;
3874 }
3875 }
3876
3877 @Override
3878 public void showLockTaskEscapeMessage(IBinder token) {
3879 synchronized (mGlobalLock) {
3880 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3881 if (r == null) {
3882 return;
3883 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003884 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 }
3886 }
3887
3888 @Override
3889 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003890 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 final long token = Binder.clearCallingIdentity();
3892 try {
3893 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003894 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895 }
3896 } finally {
3897 Binder.restoreCallingIdentity(token);
3898 }
3899 }
3900
3901 /**
3902 * Try to place task to provided position. The final position might be different depending on
3903 * current user and stacks state. The task will be moved to target stack if it's currently in
3904 * different stack.
3905 */
3906 @Override
3907 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 synchronized (mGlobalLock) {
3910 long ident = Binder.clearCallingIdentity();
3911 try {
3912 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3913 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003914 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 if (task == null) {
3916 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3917 + taskId);
3918 }
3919
Wale Ogunwaled32da472018-11-16 07:19:28 -08003920 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921
3922 if (stack == null) {
3923 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3924 + stackId);
3925 }
3926 if (!stack.isActivityTypeStandardOrUndefined()) {
3927 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3928 + " the position of task " + taskId + " in/to non-standard stack");
3929 }
3930
3931 // TODO: Have the callers of this API call a separate reparent method if that is
3932 // what they intended to do vs. having this method also do reparenting.
3933 if (task.getStack() == stack) {
3934 // Change position in current stack.
3935 stack.positionChildAt(task, position);
3936 } else {
3937 // Reparent to new stack.
3938 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3939 !DEFER_RESUME, "positionTaskInStack");
3940 }
3941 } finally {
3942 Binder.restoreCallingIdentity(ident);
3943 }
3944 }
3945 }
3946
3947 @Override
3948 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3949 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3950 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003951 + Arrays.toString(horizontalSizeConfiguration) + " "
3952 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 synchronized (mGlobalLock) {
3954 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3955 if (record == null) {
3956 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3957 + "found for: " + token);
3958 }
3959 record.setSizeConfigurations(horizontalSizeConfiguration,
3960 verticalSizeConfigurations, smallestSizeConfigurations);
3961 }
3962 }
3963
3964 /**
3965 * Dismisses split-screen multi-window mode.
3966 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3967 */
3968 @Override
3969 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003970 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3972 final long ident = Binder.clearCallingIdentity();
3973 try {
3974 synchronized (mGlobalLock) {
3975 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003976 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 if (stack == null) {
3978 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3979 return;
3980 }
3981
3982 if (toTop) {
3983 // Caller wants the current split-screen primary stack to be the top stack after
3984 // it goes fullscreen, so move it to the front.
3985 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003986 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003988 // stack after it goes fullscreen, so we move the focus to the top-most
3989 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3991 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3992 if (otherStack != null) {
3993 otherStack.moveToFront("dismissSplitScreenMode_other");
3994 }
3995 }
3996
Evan Rosky10475742018-09-05 19:02:48 -07003997 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 }
3999 } finally {
4000 Binder.restoreCallingIdentity(ident);
4001 }
4002 }
4003
4004 /**
4005 * Dismisses Pip
4006 * @param animate True if the dismissal should be animated.
4007 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4008 * default animation duration should be used.
4009 */
4010 @Override
4011 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 final long ident = Binder.clearCallingIdentity();
4014 try {
4015 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004016 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004017 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004018 if (stack == null) {
4019 Slog.w(TAG, "dismissPip: pinned stack not found.");
4020 return;
4021 }
4022 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4023 throw new IllegalArgumentException("Stack: " + stack
4024 + " doesn't support animated resize.");
4025 }
4026 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004027 stack.animateResizePinnedStack(null /* destBounds */,
4028 null /* sourceHintBounds */, animationDuration,
4029 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004030 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004031 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 }
4033 }
4034 } finally {
4035 Binder.restoreCallingIdentity(ident);
4036 }
4037 }
4038
4039 @Override
4040 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 synchronized (mGlobalLock) {
4043 mSuppressResizeConfigChanges = suppress;
4044 }
4045 }
4046
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 @Override
4048 // TODO: API should just be about changing windowing modes...
4049 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 "moveTasksToFullscreenStack()");
4052 synchronized (mGlobalLock) {
4053 final long origId = Binder.clearCallingIdentity();
4054 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004055 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 if (stack != null){
4057 if (!stack.isActivityTypeStandardOrUndefined()) {
4058 throw new IllegalArgumentException(
4059 "You can't move tasks from non-standard stacks.");
4060 }
4061 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4062 }
4063 } finally {
4064 Binder.restoreCallingIdentity(origId);
4065 }
4066 }
4067 }
4068
4069 /**
4070 * Moves the top activity in the input stackId to the pinned stack.
4071 *
4072 * @param stackId Id of stack to move the top activity to pinned stack.
4073 * @param bounds Bounds to use for pinned stack.
4074 *
4075 * @return True if the top activity of the input stack was successfully moved to the pinned
4076 * stack.
4077 */
4078 @Override
4079 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004080 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 "moveTopActivityToPinnedStack()");
4082 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004083 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004084 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4085 + "Device doesn't support picture-in-picture mode");
4086 }
4087
4088 long ident = Binder.clearCallingIdentity();
4089 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004090 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 } finally {
4092 Binder.restoreCallingIdentity(ident);
4093 }
4094 }
4095 }
4096
4097 @Override
4098 public boolean isInMultiWindowMode(IBinder token) {
4099 final long origId = Binder.clearCallingIdentity();
4100 try {
4101 synchronized (mGlobalLock) {
4102 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4103 if (r == null) {
4104 return false;
4105 }
4106 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4107 return r.inMultiWindowMode();
4108 }
4109 } finally {
4110 Binder.restoreCallingIdentity(origId);
4111 }
4112 }
4113
4114 @Override
4115 public boolean isInPictureInPictureMode(IBinder token) {
4116 final long origId = Binder.clearCallingIdentity();
4117 try {
4118 synchronized (mGlobalLock) {
4119 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4120 }
4121 } finally {
4122 Binder.restoreCallingIdentity(origId);
4123 }
4124 }
4125
4126 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004127 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4128 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 return false;
4130 }
4131
4132 // If we are animating to fullscreen then we have already dispatched the PIP mode
4133 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004134 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004135 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004136 }
4137
4138 @Override
4139 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4140 final long origId = Binder.clearCallingIdentity();
4141 try {
4142 synchronized (mGlobalLock) {
4143 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4144 "enterPictureInPictureMode", token, params);
4145
4146 // If the activity is already in picture in picture mode, then just return early
4147 if (isInPictureInPictureMode(r)) {
4148 return true;
4149 }
4150
4151 // Activity supports picture-in-picture, now check that we can enter PiP at this
4152 // point, if it is
4153 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4154 false /* beforeStopping */)) {
4155 return false;
4156 }
4157
4158 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004159 synchronized (mGlobalLock) {
4160 // Only update the saved args from the args that are set
4161 r.pictureInPictureArgs.copyOnlySet(params);
4162 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4163 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4164 // Adjust the source bounds by the insets for the transition down
4165 final Rect sourceBounds = new Rect(
4166 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004167 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004168 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004170 stack.setPictureInPictureAspectRatio(aspectRatio);
4171 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004172 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4173 r.info.applicationInfo.uid, r.shortComponentName,
4174 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004175 logPictureInPictureArgs(params);
4176 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 };
4178
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004179 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 // If the keyguard is showing or occluded, then try and dismiss it before
4181 // entering picture-in-picture (this will prompt the user to authenticate if the
4182 // device is currently locked).
4183 dismissKeyguard(token, new KeyguardDismissCallback() {
4184 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004185 public void onDismissSucceeded() {
4186 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 }
4188 }, null /* message */);
4189 } else {
4190 // Enter picture in picture immediately otherwise
4191 enterPipRunnable.run();
4192 }
4193 return true;
4194 }
4195 } finally {
4196 Binder.restoreCallingIdentity(origId);
4197 }
4198 }
4199
4200 @Override
4201 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4202 final long origId = Binder.clearCallingIdentity();
4203 try {
4204 synchronized (mGlobalLock) {
4205 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4206 "setPictureInPictureParams", token, params);
4207
4208 // Only update the saved args from the args that are set
4209 r.pictureInPictureArgs.copyOnlySet(params);
4210 if (r.inPinnedWindowingMode()) {
4211 // If the activity is already in picture-in-picture, update the pinned stack now
4212 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4213 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004214 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 if (!stack.isAnimatingBoundsToFullscreen()) {
4216 stack.setPictureInPictureAspectRatio(
4217 r.pictureInPictureArgs.getAspectRatio());
4218 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4219 }
4220 }
4221 logPictureInPictureArgs(params);
4222 }
4223 } finally {
4224 Binder.restoreCallingIdentity(origId);
4225 }
4226 }
4227
4228 @Override
4229 public int getMaxNumPictureInPictureActions(IBinder token) {
4230 // Currently, this is a static constant, but later, we may change this to be dependent on
4231 // the context of the activity
4232 return 3;
4233 }
4234
4235 private void logPictureInPictureArgs(PictureInPictureParams params) {
4236 if (params.hasSetActions()) {
4237 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4238 params.getActions().size());
4239 }
4240 if (params.hasSetAspectRatio()) {
4241 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4242 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4243 MetricsLogger.action(lm);
4244 }
4245 }
4246
4247 /**
4248 * Checks the state of the system and the activity associated with the given {@param token} to
4249 * verify that picture-in-picture is supported for that activity.
4250 *
4251 * @return the activity record for the given {@param token} if all the checks pass.
4252 */
4253 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4254 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004255 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 throw new IllegalStateException(caller
4257 + ": Device doesn't support picture-in-picture mode.");
4258 }
4259
4260 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4261 if (r == null) {
4262 throw new IllegalStateException(caller
4263 + ": Can't find activity for token=" + token);
4264 }
4265
4266 if (!r.supportsPictureInPicture()) {
4267 throw new IllegalStateException(caller
4268 + ": Current activity does not support picture-in-picture.");
4269 }
4270
4271 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004272 && !mWindowManager.isValidPictureInPictureAspectRatio(
4273 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 final float minAspectRatio = mContext.getResources().getFloat(
4275 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4276 final float maxAspectRatio = mContext.getResources().getFloat(
4277 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4278 throw new IllegalArgumentException(String.format(caller
4279 + ": Aspect ratio is too extreme (must be between %f and %f).",
4280 minAspectRatio, maxAspectRatio));
4281 }
4282
4283 // Truncate the number of actions if necessary
4284 params.truncateActions(getMaxNumPictureInPictureActions(token));
4285
4286 return r;
4287 }
4288
4289 @Override
4290 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004291 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 synchronized (mGlobalLock) {
4293 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4294 if (r == null) {
4295 throw new IllegalArgumentException("Activity does not exist; token="
4296 + activityToken);
4297 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004298 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
4300 }
4301
4302 @Override
4303 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4304 Rect tempDockedTaskInsetBounds,
4305 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 long ident = Binder.clearCallingIdentity();
4308 try {
4309 synchronized (mGlobalLock) {
4310 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4311 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4312 PRESERVE_WINDOWS);
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
4319 @Override
4320 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004321 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 final long ident = Binder.clearCallingIdentity();
4323 try {
4324 synchronized (mGlobalLock) {
4325 mStackSupervisor.setSplitScreenResizing(resizing);
4326 }
4327 } finally {
4328 Binder.restoreCallingIdentity(ident);
4329 }
4330 }
4331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 /**
4333 * Check that we have the features required for VR-related API calls, and throw an exception if
4334 * not.
4335 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004336 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004337 if (!mContext.getPackageManager().hasSystemFeature(
4338 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4339 throw new UnsupportedOperationException("VR mode not supported on this device!");
4340 }
4341 }
4342
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 @Override
4344 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346
4347 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4348
4349 ActivityRecord r;
4350 synchronized (mGlobalLock) {
4351 r = ActivityRecord.isInStackLocked(token);
4352 }
4353
4354 if (r == null) {
4355 throw new IllegalArgumentException();
4356 }
4357
4358 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004359 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 VrManagerInternal.NO_ERROR) {
4361 return err;
4362 }
4363
4364 // Clear the binder calling uid since this path may call moveToTask().
4365 final long callingId = Binder.clearCallingIdentity();
4366 try {
4367 synchronized (mGlobalLock) {
4368 r.requestedVrComponent = (enabled) ? packageName : null;
4369
4370 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004371 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374 return 0;
4375 }
4376 } finally {
4377 Binder.restoreCallingIdentity(callingId);
4378 }
4379 }
4380
4381 @Override
4382 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4383 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4384 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004385 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4387 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4388 }
Louis Changcdec0802019-11-11 11:45:07 +08004389 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 || activity.voiceSession != null) {
4391 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4392 return;
4393 }
4394 if (activity.pendingVoiceInteractionStart) {
4395 Slog.w(TAG, "Pending start of voice interaction already.");
4396 return;
4397 }
4398 activity.pendingVoiceInteractionStart = true;
4399 }
4400 LocalServices.getService(VoiceInteractionManagerInternal.class)
4401 .startLocalVoiceInteraction(callingActivity, options);
4402 }
4403
4404 @Override
4405 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4406 LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .stopLocalVoiceInteraction(callingActivity);
4408 }
4409
4410 @Override
4411 public boolean supportsLocalVoiceInteraction() {
4412 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4413 .supportsLocalVoiceInteraction();
4414 }
4415
4416 /** Notifies all listeners when the pinned stack animation starts. */
4417 @Override
4418 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004419 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421
4422 /** Notifies all listeners when the pinned stack animation ends. */
4423 @Override
4424 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004425 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 }
4427
4428 @Override
4429 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 final long ident = Binder.clearCallingIdentity();
4432 try {
4433 synchronized (mGlobalLock) {
4434 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4435 }
4436 } finally {
4437 Binder.restoreCallingIdentity(ident);
4438 }
4439 }
4440
4441 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444
4445 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004446 if (mWindowManager == null) {
4447 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4448 return false;
4449 }
4450
4451 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 }
4455
Riddle Hsua0022cd2019-09-09 21:12:41 +08004456 mH.sendMessage(PooledLambda.obtainMessage(
4457 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4458 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459
4460 final long origId = Binder.clearCallingIdentity();
4461 try {
4462 if (values != null) {
4463 Settings.System.clearConfiguration(values);
4464 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 UserHandle.USER_NULL, false /* deferResume */,
4467 mTmpUpdateConfigurationResult);
4468 return mTmpUpdateConfigurationResult.changes != 0;
4469 } finally {
4470 Binder.restoreCallingIdentity(origId);
4471 }
4472 }
4473 }
4474
4475 @Override
4476 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4477 CharSequence message) {
4478 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4481 }
4482 final long callingId = Binder.clearCallingIdentity();
4483 try {
4484 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004485 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 }
4487 } finally {
4488 Binder.restoreCallingIdentity(callingId);
4489 }
4490 }
4491
4492 @Override
4493 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 "cancelTaskWindowTransition()");
4496 final long ident = Binder.clearCallingIdentity();
4497 try {
4498 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004499 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 MATCH_TASK_IN_STACKS_ONLY);
4501 if (task == null) {
4502 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4503 return;
4504 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004505 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 }
4507 } finally {
4508 Binder.restoreCallingIdentity(ident);
4509 }
4510 }
4511
4512 @Override
4513 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 final long ident = Binder.clearCallingIdentity();
4516 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 } finally {
4519 Binder.restoreCallingIdentity(ident);
4520 }
4521 }
4522
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004523 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4524 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004525 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004526 synchronized (mGlobalLock) {
4527 task = mRootActivityContainer.anyTaskForId(taskId,
4528 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4529 if (task == null) {
4530 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4531 return null;
4532 }
4533 }
4534 // Don't call this while holding the lock as this operation might hit the disk.
4535 return task.getSnapshot(reducedResolution, restoreFromDisk);
4536 }
4537
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 @Override
4539 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4540 synchronized (mGlobalLock) {
4541 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4542 if (r == null) {
4543 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4544 + token);
4545 return;
4546 }
4547 final long origId = Binder.clearCallingIdentity();
4548 try {
4549 r.setDisablePreviewScreenshots(disable);
4550 } finally {
4551 Binder.restoreCallingIdentity(origId);
4552 }
4553 }
4554 }
4555
4556 /** Return the user id of the last resumed activity. */
4557 @Override
4558 public @UserIdInt
4559 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4562 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004563 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004564 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004565 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004566 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 }
4568 }
4569
4570 @Override
4571 public void updateLockTaskFeatures(int userId, int flags) {
4572 final int callingUid = Binder.getCallingUid();
4573 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004574 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 "updateLockTaskFeatures()");
4576 }
4577 synchronized (mGlobalLock) {
4578 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4579 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004580 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 }
4582 }
4583
4584 @Override
4585 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4586 synchronized (mGlobalLock) {
4587 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4588 if (r == null) {
4589 return;
4590 }
4591 final long origId = Binder.clearCallingIdentity();
4592 try {
4593 r.setShowWhenLocked(showWhenLocked);
4594 } finally {
4595 Binder.restoreCallingIdentity(origId);
4596 }
4597 }
4598 }
4599
4600 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004601 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4602 synchronized (mGlobalLock) {
4603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4604 if (r == null) {
4605 return;
4606 }
4607 final long origId = Binder.clearCallingIdentity();
4608 try {
4609 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4610 } finally {
4611 Binder.restoreCallingIdentity(origId);
4612 }
4613 }
4614 }
4615
4616 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4618 synchronized (mGlobalLock) {
4619 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4620 if (r == null) {
4621 return;
4622 }
4623 final long origId = Binder.clearCallingIdentity();
4624 try {
4625 r.setTurnScreenOn(turnScreenOn);
4626 } finally {
4627 Binder.restoreCallingIdentity(origId);
4628 }
4629 }
4630 }
4631
4632 @Override
4633 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004634 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004636 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 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.registerRemoteAnimations(definition);
4645 } finally {
4646 Binder.restoreCallingIdentity(origId);
4647 }
4648 }
4649 }
4650
4651 @Override
4652 public void registerRemoteAnimationForNextActivityStart(String packageName,
4653 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004656 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004657 synchronized (mGlobalLock) {
4658 final long origId = Binder.clearCallingIdentity();
4659 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004660 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004661 packageName, adapter);
4662 } finally {
4663 Binder.restoreCallingIdentity(origId);
4664 }
4665 }
4666 }
4667
Evan Rosky966759f2019-01-15 10:33:58 -08004668 @Override
4669 public void registerRemoteAnimationsForDisplay(int displayId,
4670 RemoteAnimationDefinition definition) {
4671 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4672 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004673 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004674 synchronized (mGlobalLock) {
4675 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4676 if (display == null) {
4677 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4678 return;
4679 }
4680 final long origId = Binder.clearCallingIdentity();
4681 try {
4682 display.mDisplayContent.registerRemoteAnimations(definition);
4683 } finally {
4684 Binder.restoreCallingIdentity(origId);
4685 }
4686 }
4687 }
4688
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4690 @Override
4691 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4692 synchronized (mGlobalLock) {
4693 final long origId = Binder.clearCallingIdentity();
4694 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004695 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004696 } finally {
4697 Binder.restoreCallingIdentity(origId);
4698 }
4699 }
4700 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004701
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 @Override
4703 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004704 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004706 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004707 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004708 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 }
4710 }
4711
4712 @Override
4713 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004715 != PERMISSION_GRANTED) {
4716 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4717 + Binder.getCallingPid()
4718 + ", uid=" + Binder.getCallingUid()
4719 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4720 Slog.w(TAG, msg);
4721 throw new SecurityException(msg);
4722 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004723 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004725 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004726 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004727 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 }
4729 }
4730
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004731 @Override
4732 public void stopAppSwitches() {
4733 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4734 synchronized (mGlobalLock) {
4735 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004736 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004737 mDidAppSwitch = false;
4738 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4739 }
4740 }
4741
4742 @Override
4743 public void resumeAppSwitches() {
4744 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4745 synchronized (mGlobalLock) {
4746 // Note that we don't execute any pending app switches... we will
4747 // let those wait until either the timeout, or the next start
4748 // activity request.
4749 mAppSwitchesAllowedTime = 0;
4750 }
4751 }
4752
Ricky Wai906af482019-06-03 17:25:28 +01004753 long getLastStopAppSwitchesTime() {
4754 return mLastStopAppSwitchesTime;
4755 }
4756
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 void onStartActivitySetDidAppSwitch() {
4758 if (mDidAppSwitch) {
4759 // This is the second allowed switch since we stopped switches, so now just generally
4760 // allow switches. Use case:
4761 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4762 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4763 // anyone to switch again).
4764 mAppSwitchesAllowedTime = 0;
4765 } else {
4766 mDidAppSwitch = true;
4767 }
4768 }
4769
4770 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004771 boolean shouldDisableNonVrUiLocked() {
4772 return mVrController.shouldDisableNonVrUiLocked();
4773 }
4774
Wale Ogunwale53783742018-09-16 10:21:51 -07004775 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004776 // 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 +00004777 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004778 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004779 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4780 + " to main display for VR");
4781 mRootActivityContainer.moveStackToDisplay(
4782 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004783 }
4784 mH.post(() -> {
4785 if (!mVrController.onVrModeChanged(r)) {
4786 return;
4787 }
4788 synchronized (mGlobalLock) {
4789 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4790 mWindowManager.disableNonVrUi(disableNonVrUi);
4791 if (disableNonVrUi) {
4792 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4793 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004794 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 }
4796 }
4797 });
4798 }
4799
Wale Ogunwale53783742018-09-16 10:21:51 -07004800 @Override
4801 public int getPackageScreenCompatMode(String packageName) {
4802 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4803 synchronized (mGlobalLock) {
4804 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4805 }
4806 }
4807
4808 @Override
4809 public void setPackageScreenCompatMode(String packageName, int mode) {
4810 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4811 "setPackageScreenCompatMode");
4812 synchronized (mGlobalLock) {
4813 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4814 }
4815 }
4816
4817 @Override
4818 public boolean getPackageAskScreenCompat(String packageName) {
4819 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4820 synchronized (mGlobalLock) {
4821 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4822 }
4823 }
4824
4825 @Override
4826 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4827 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4828 "setPackageAskScreenCompat");
4829 synchronized (mGlobalLock) {
4830 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4831 }
4832 }
4833
Wale Ogunwale64258362018-10-16 15:13:37 -07004834 public static String relaunchReasonToString(int relaunchReason) {
4835 switch (relaunchReason) {
4836 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4837 return "window_resize";
4838 case RELAUNCH_REASON_FREE_RESIZE:
4839 return "free_resize";
4840 default:
4841 return null;
4842 }
4843 }
4844
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004845 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004846 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004847 }
4848
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004849 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004850 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004851 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4852 }
4853
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004854 boolean isKeyguardLocked() {
4855 return mKeyguardController.isKeyguardLocked();
4856 }
4857
Garfield Tan01548632018-11-27 10:15:48 -08004858 /**
4859 * Clears launch params for the given package.
4860 * @param packageNames the names of the packages of which the launch params are to be cleared
4861 */
4862 @Override
4863 public void clearLaunchParamsForPackages(List<String> packageNames) {
4864 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4865 "clearLaunchParamsForPackages");
4866 synchronized (mGlobalLock) {
4867 for (int i = 0; i < packageNames.size(); ++i) {
4868 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4869 }
4870 }
4871 }
4872
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004873 /**
4874 * Makes the display with the given id a single task instance display. I.e the display can only
4875 * contain one task.
4876 */
4877 @Override
4878 public void setDisplayToSingleTaskInstance(int displayId) {
4879 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4880 "setDisplayToSingleTaskInstance");
4881 final long origId = Binder.clearCallingIdentity();
4882 try {
4883 final ActivityDisplay display =
4884 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4885 if (display != null) {
4886 display.setDisplayToSingleTaskInstance();
4887 }
4888 } finally {
4889 Binder.restoreCallingIdentity(origId);
4890 }
4891 }
4892
Wale Ogunwale31913b52018-10-13 08:29:31 -07004893 void dumpLastANRLocked(PrintWriter pw) {
4894 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4895 if (mLastANRState == null) {
4896 pw.println(" <no ANR has occurred since boot>");
4897 } else {
4898 pw.println(mLastANRState);
4899 }
4900 }
4901
4902 void dumpLastANRTracesLocked(PrintWriter pw) {
4903 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4904
4905 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4906 if (ArrayUtils.isEmpty(files)) {
4907 pw.println(" <no ANR has occurred since boot>");
4908 return;
4909 }
4910 // Find the latest file.
4911 File latest = null;
4912 for (File f : files) {
4913 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4914 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004915 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004916 }
4917 pw.print("File: ");
4918 pw.print(latest.getName());
4919 pw.println();
4920 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4921 String line;
4922 while ((line = in.readLine()) != null) {
4923 pw.println(line);
4924 }
4925 } catch (IOException e) {
4926 pw.print("Unable to read: ");
4927 pw.print(e);
4928 pw.println();
4929 }
4930 }
4931
4932 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4933 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4934 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4935 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4936 }
4937
4938 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4939 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4940 pw.println(header);
4941
Wale Ogunwaled32da472018-11-16 07:19:28 -08004942 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004943 dumpPackage);
4944 boolean needSep = printedAnything;
4945
4946 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004947 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004948 " ResumedActivity: ");
4949 if (printed) {
4950 printedAnything = true;
4951 needSep = false;
4952 }
4953
4954 if (dumpPackage == null) {
4955 if (needSep) {
4956 pw.println();
4957 }
4958 printedAnything = true;
4959 mStackSupervisor.dump(pw, " ");
4960 }
4961
4962 if (!printedAnything) {
4963 pw.println(" (nothing)");
4964 }
4965 }
4966
4967 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004968 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004969 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004970 pw.println(" ");
4971 }
4972
4973 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4974 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4975 getActivityStartController().dump(pw, "", dumpPackage);
4976 }
4977
4978 /**
4979 * There are three things that cmd can be:
4980 * - a flattened component name that matches an existing activity
4981 * - the cmd arg isn't the flattened component name of an existing activity:
4982 * dump all activity whose component contains the cmd as a substring
4983 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004984 * <p>
4985 * The caller should not hold lock when calling this method because it will wait for the
4986 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004987 *
4988 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4989 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4990 */
4991 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4992 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4993 ArrayList<ActivityRecord> activities;
4994
4995 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004996 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 dumpFocusedStackOnly);
4998 }
4999
5000 if (activities.size() <= 0) {
5001 return false;
5002 }
5003
5004 String[] newArgs = new String[args.length - opti];
5005 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5006
Louis Changcdec0802019-11-11 11:45:07 +08005007 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005008 boolean needSep = false;
5009 for (int i = activities.size() - 1; i >= 0; i--) {
5010 ActivityRecord r = activities.get(i);
5011 if (needSep) {
5012 pw.println();
5013 }
5014 needSep = true;
5015 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005016 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 if (lastTask != task) {
5018 lastTask = task;
5019 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005020 pw.print(" id="); pw.print(lastTask.mTaskId);
5021 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 if (dumpAll) {
5023 lastTask.dump(pw, " ");
5024 }
5025 }
5026 }
5027 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5028 }
5029 return true;
5030 }
5031
5032 /**
5033 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5034 * there is a thread associated with the activity.
5035 */
5036 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5037 final ActivityRecord r, String[] args, boolean dumpAll) {
5038 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005039 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005040 synchronized (mGlobalLock) {
5041 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5042 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5043 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005044 if (r.hasProcess()) {
5045 pw.println(r.app.getPid());
5046 appThread = r.app.getThread();
5047 } else {
5048 pw.println("(not running)");
5049 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005050 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005051 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005052 }
5053 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005054 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005055 // flush anything that is already in the PrintWriter since the thread is going
5056 // to write to the file descriptor directly
5057 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005058 try (TransferPipe tp = new TransferPipe()) {
5059 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5060 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005061 } catch (IOException e) {
5062 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5063 } catch (RemoteException e) {
5064 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5065 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005066 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005067 }
5068
sanryhuang498e77e2018-12-06 14:57:01 +08005069 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5070 boolean testPssMode) {
5071 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5072 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5073 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005074 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005075 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5076 st.toString());
5077 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5079 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5080 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005081 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5082 testPssMode);
5083 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005084 }
5085
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086 int getCurrentUserId() {
5087 return mAmInternal.getCurrentUserId();
5088 }
5089
5090 private void enforceNotIsolatedCaller(String caller) {
5091 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5092 throw new SecurityException("Isolated process not allowed to call " + caller);
5093 }
5094 }
5095
Wale Ogunwalef6733932018-06-27 05:14:34 -07005096 public Configuration getConfiguration() {
5097 Configuration ci;
5098 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005099 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005100 ci.userSetLocale = false;
5101 }
5102 return ci;
5103 }
5104
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 /**
5106 * Current global configuration information. Contains general settings for the entire system,
5107 * also corresponds to the merged configuration of the default display.
5108 */
5109 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005110 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005111 }
5112
5113 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5114 boolean initLocale) {
5115 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5116 }
5117
5118 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5119 boolean initLocale, boolean deferResume) {
5120 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5121 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5122 UserHandle.USER_NULL, deferResume);
5123 }
5124
Wale Ogunwale59507092018-10-29 09:00:30 -07005125 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005126 final long origId = Binder.clearCallingIdentity();
5127 try {
5128 synchronized (mGlobalLock) {
5129 updateConfigurationLocked(values, null, false, true, userId,
5130 false /* deferResume */);
5131 }
5132 } finally {
5133 Binder.restoreCallingIdentity(origId);
5134 }
5135 }
5136
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5138 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5139 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5140 deferResume, null /* result */);
5141 }
5142
5143 /**
5144 * Do either or both things: (1) change the current configuration, and (2)
5145 * make sure the given activity is running with the (now) current
5146 * configuration. Returns true if the activity has been left running, or
5147 * false if <var>starting</var> is being destroyed to match the new
5148 * configuration.
5149 *
5150 * @param userId is only used when persistent parameter is set to true to persist configuration
5151 * for that particular user
5152 */
5153 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5154 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5155 ActivityTaskManagerService.UpdateConfigurationResult result) {
5156 int changes = 0;
5157 boolean kept = true;
5158
Riddle Hsua0022cd2019-09-09 21:12:41 +08005159 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005160 try {
5161 if (values != null) {
5162 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5163 deferResume);
5164 }
5165
5166 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5167 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005168 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005169 }
5170
5171 if (result != null) {
5172 result.changes = changes;
5173 result.activityRelaunched = !kept;
5174 }
5175 return kept;
5176 }
5177
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005179 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005181
5182 final ActivityDisplay defaultDisplay =
5183 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5184
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005185 mTempConfig.setTo(getGlobalConfiguration());
5186 final int changes = mTempConfig.updateFrom(values);
5187 if (changes == 0) {
5188 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5189 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5190 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5191 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005192 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193 return 0;
5194 }
5195
5196 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5197 "Updating global configuration to: " + values);
5198
5199 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5200 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5201 values.colorMode,
5202 values.densityDpi,
5203 values.fontScale,
5204 values.hardKeyboardHidden,
5205 values.keyboard,
5206 values.keyboardHidden,
5207 values.mcc,
5208 values.mnc,
5209 values.navigation,
5210 values.navigationHidden,
5211 values.orientation,
5212 values.screenHeightDp,
5213 values.screenLayout,
5214 values.screenWidthDp,
5215 values.smallestScreenWidthDp,
5216 values.touchscreen,
5217 values.uiMode);
5218
5219
5220 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5221 final LocaleList locales = values.getLocales();
5222 int bestLocaleIndex = 0;
5223 if (locales.size() > 1) {
5224 if (mSupportedSystemLocales == null) {
5225 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5226 }
5227 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5228 }
5229 SystemProperties.set("persist.sys.locale",
5230 locales.get(bestLocaleIndex).toLanguageTag());
5231 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005232
5233 final Message m = PooledLambda.obtainMessage(
5234 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5235 locales.get(bestLocaleIndex));
5236 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005237 }
5238
Yunfan Chen75157d72018-07-27 14:47:21 +09005239 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240
5241 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005242 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005243
5244 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5245 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005246 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005247
5248 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005249 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250
5251 AttributeCache ac = AttributeCache.instance();
5252 if (ac != null) {
5253 ac.updateConfiguration(mTempConfig);
5254 }
5255
5256 // Make sure all resources in our process are updated right now, so that anyone who is going
5257 // to retrieve resource values after we return will be sure to get the new ones. This is
5258 // especially important during boot, where the first config change needs to guarantee all
5259 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005260 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005261
5262 // We need another copy of global config because we're scheduling some calls instead of
5263 // running them in place. We need to be sure that object we send will be handled unchanged.
5264 final Configuration configCopy = new Configuration(mTempConfig);
5265 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005266 final Message msg = PooledLambda.obtainMessage(
5267 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5268 this, userId, configCopy);
5269 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005270 }
5271
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005272 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5273 for (int i = pidMap.size() - 1; i >= 0; i--) {
5274 final int pid = pidMap.keyAt(i);
5275 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005276 if (DEBUG_CONFIGURATION) {
5277 Slog.v(TAG_CONFIGURATION, "Update process config of "
5278 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005279 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005280 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005281 }
5282
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005283 final Message msg = PooledLambda.obtainMessage(
5284 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5285 mAmInternal, changes, initLocale);
5286 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287
5288 // Override configuration of the default display duplicates global config, so we need to
5289 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005290 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5291 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292
5293 return changes;
5294 }
5295
Riddle Hsua0022cd2019-09-09 21:12:41 +08005296 /** @see WindowSurfacePlacer#deferLayout */
5297 void deferWindowLayout() {
5298 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5299 // Reset the reasons at the first entrance because we only care about the changes in the
5300 // deferred scope.
5301 mLayoutReasons = 0;
5302 }
5303
5304 mWindowManager.mWindowPlacerLocked.deferLayout();
5305 }
5306
5307 /** @see WindowSurfacePlacer#continueLayout */
5308 void continueWindowLayout() {
5309 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5310 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5311 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5312 }
5313 }
5314
5315 /**
5316 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5317 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5318 * defer count is gone.
5319 */
5320 void addWindowLayoutReasons(@LayoutReason int reasons) {
5321 mLayoutReasons |= reasons;
5322 }
5323
Wale Ogunwalef6733932018-06-27 05:14:34 -07005324 private void updateEventDispatchingLocked(boolean booted) {
5325 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5326 }
5327
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005328 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5329 final ContentResolver resolver = mContext.getContentResolver();
5330 Settings.System.putConfigurationForUser(resolver, config, userId);
5331 }
5332
5333 private void sendLocaleToMountDaemonMsg(Locale l) {
5334 try {
5335 IBinder service = ServiceManager.getService("mount");
5336 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5337 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5338 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5339 } catch (RemoteException e) {
5340 Log.e(TAG, "Error storing locale for decryption UI", e);
5341 }
5342 }
5343
Alison Cichowlas3e340502018-08-07 17:15:01 -04005344 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5345 mStartActivitySources.remove(permissionToken);
5346 mExpiredStartAsCallerTokens.add(permissionToken);
5347 }
5348
5349 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5350 mExpiredStartAsCallerTokens.remove(permissionToken);
5351 }
5352
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005353 boolean isActivityStartsLoggingEnabled() {
5354 return mAmInternal.isActivityStartsLoggingEnabled();
5355 }
5356
Michal Karpinski8596ded2018-11-14 14:43:48 +00005357 boolean isBackgroundActivityStartsEnabled() {
5358 return mAmInternal.isBackgroundActivityStartsEnabled();
5359 }
5360
Wale Ogunwalef6733932018-06-27 05:14:34 -07005361 void enableScreenAfterBoot(boolean booted) {
5362 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5363 SystemClock.uptimeMillis());
5364 mWindowManager.enableScreenAfterBoot();
5365
5366 synchronized (mGlobalLock) {
5367 updateEventDispatchingLocked(booted);
5368 }
5369 }
5370
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005371 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5372 if (r == null || !r.hasProcess()) {
5373 return KEY_DISPATCHING_TIMEOUT_MS;
5374 }
5375 return getInputDispatchingTimeoutLocked(r.app);
5376 }
5377
5378 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005379 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005380 }
5381
Wale Ogunwalef6733932018-06-27 05:14:34 -07005382 /**
5383 * Decide based on the configuration whether we should show the ANR,
5384 * crash, etc dialogs. The idea is that if there is no affordance to
5385 * press the on-screen buttons, or the user experience would be more
5386 * greatly impacted than the crash itself, we shouldn't show the dialog.
5387 *
5388 * A thought: SystemUI might also want to get told about this, the Power
5389 * dialog / global actions also might want different behaviors.
5390 */
5391 private void updateShouldShowDialogsLocked(Configuration config) {
5392 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5393 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5394 && config.navigation == Configuration.NAVIGATION_NONAV);
5395 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5396 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5397 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5398 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5399 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5400 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5401 HIDE_ERROR_DIALOGS, 0) != 0;
5402 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5403 }
5404
5405 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5406 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5407 FONT_SCALE, 1.0f, userId);
5408
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005409 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005410 if (getGlobalConfiguration().fontScale == scaleFactor) {
5411 return;
5412 }
5413
5414 final Configuration configuration
5415 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5416 configuration.fontScale = scaleFactor;
5417 updatePersistentConfiguration(configuration, userId);
5418 }
5419 }
5420
5421 // Actually is sleeping or shutting down or whatever else in the future
5422 // is an inactive state.
5423 boolean isSleepingOrShuttingDownLocked() {
5424 return isSleepingLocked() || mShuttingDown;
5425 }
5426
5427 boolean isSleepingLocked() {
5428 return mSleeping;
5429 }
5430
Riddle Hsu16567132018-08-16 21:37:47 +08005431 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005433 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005434 if (task.isActivityTypeStandard()) {
5435 if (mCurAppTimeTracker != r.appTimeTracker) {
5436 // We are switching app tracking. Complete the current one.
5437 if (mCurAppTimeTracker != null) {
5438 mCurAppTimeTracker.stop();
5439 mH.obtainMessage(
5440 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005441 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005442 mCurAppTimeTracker = null;
5443 }
5444 if (r.appTimeTracker != null) {
5445 mCurAppTimeTracker = r.appTimeTracker;
5446 startTimeTrackingFocusedActivityLocked();
5447 }
5448 } else {
5449 startTimeTrackingFocusedActivityLocked();
5450 }
5451 } else {
5452 r.appTimeTracker = null;
5453 }
5454 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5455 // TODO: Probably not, because we don't want to resume voice on switching
5456 // back to this activity
5457 if (task.voiceInteractor != null) {
5458 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5459 } else {
5460 finishRunningVoiceLocked();
5461
5462 if (mLastResumedActivity != null) {
5463 final IVoiceInteractionSession session;
5464
Louis Changcdec0802019-11-11 11:45:07 +08005465 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 if (lastResumedActivityTask != null
5467 && lastResumedActivityTask.voiceSession != null) {
5468 session = lastResumedActivityTask.voiceSession;
5469 } else {
5470 session = mLastResumedActivity.voiceSession;
5471 }
5472
5473 if (session != null) {
5474 // We had been in a voice interaction session, but now focused has
5475 // move to something different. Just finish the session, we can't
5476 // return to it and retain the proper state and synchronization with
5477 // the voice interaction service.
5478 finishVoiceTask(session);
5479 }
5480 }
5481 }
5482
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005483 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5484 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005485 }
5486 updateResumedAppTrace(r);
5487 mLastResumedActivity = r;
5488
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005489 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005490
5491 applyUpdateLockStateLocked(r);
5492 applyUpdateVrModeLocked(r);
5493
5494 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005495 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005496 r == null ? "NULL" : r.shortComponentName,
5497 reason);
5498 }
5499
5500 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5501 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005502 final ActivityTaskManagerInternal.SleepToken token =
5503 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005504 updateSleepIfNeededLocked();
5505 return token;
5506 }
5507 }
5508
5509 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005510 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 final boolean wasSleeping = mSleeping;
5512 boolean updateOomAdj = false;
5513
5514 if (!shouldSleep) {
5515 // If wasSleeping is true, we need to wake up activity manager state from when
5516 // we started sleeping. In either case, we need to apply the sleep tokens, which
5517 // will wake up stacks or put them to sleep as appropriate.
5518 if (wasSleeping) {
5519 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005520 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5521 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522 startTimeTrackingFocusedActivityLocked();
5523 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005524 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005525 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5526 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005527 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005528 if (wasSleeping) {
5529 updateOomAdj = true;
5530 }
5531 } else if (!mSleeping && shouldSleep) {
5532 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005533 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5534 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 if (mCurAppTimeTracker != null) {
5536 mCurAppTimeTracker.stop();
5537 }
5538 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005539 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005540 mStackSupervisor.goingToSleepLocked();
5541 updateResumedAppTrace(null /* resumed */);
5542 updateOomAdj = true;
5543 }
5544 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005545 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 }
5547 }
5548
5549 void updateOomAdj() {
5550 mH.post(mAmInternal::updateOomAdj);
5551 }
5552
Wale Ogunwale53783742018-09-16 10:21:51 -07005553 void updateCpuStats() {
5554 mH.post(mAmInternal::updateCpuStats);
5555 }
5556
Hui Yu03d12402018-12-06 18:00:37 -08005557 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5558 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005559 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5560 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005561 mH.sendMessage(m);
5562 }
5563
Hui Yu03d12402018-12-06 18:00:37 -08005564 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005565 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005566 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005567 if (task != null) {
5568 final ActivityRecord rootActivity = task.getRootActivity();
5569 if (rootActivity != null) {
5570 taskRoot = rootActivity.mActivityComponent;
5571 }
5572 }
5573
Hui Yu03d12402018-12-06 18:00:37 -08005574 final Message m = PooledLambda.obtainMessage(
5575 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005576 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005577 mH.sendMessage(m);
5578 }
5579
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005580 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5581 String hostingType) {
5582 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005583 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5584 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005585 + activity.processName);
5586 }
5587 // Post message to start process to avoid possible deadlock of calling into AMS with the
5588 // ATMS lock held.
5589 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5590 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5591 isTop, hostingType, activity.intent.getComponent());
5592 mH.sendMessage(m);
5593 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005594 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005595 }
5596 }
5597
Wale Ogunwale53783742018-09-16 10:21:51 -07005598 void setBooting(boolean booting) {
5599 mAmInternal.setBooting(booting);
5600 }
5601
5602 boolean isBooting() {
5603 return mAmInternal.isBooting();
5604 }
5605
5606 void setBooted(boolean booted) {
5607 mAmInternal.setBooted(booted);
5608 }
5609
5610 boolean isBooted() {
5611 return mAmInternal.isBooted();
5612 }
5613
5614 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5615 mH.post(() -> {
5616 if (finishBooting) {
5617 mAmInternal.finishBooting();
5618 }
5619 if (enableScreen) {
5620 mInternal.enableScreenAfterBoot(isBooted());
5621 }
5622 });
5623 }
5624
5625 void setHeavyWeightProcess(ActivityRecord root) {
5626 mHeavyWeightProcess = root.app;
5627 final Message m = PooledLambda.obtainMessage(
5628 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005629 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005630 mH.sendMessage(m);
5631 }
5632
5633 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5634 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5635 return;
5636 }
5637
5638 mHeavyWeightProcess = null;
5639 final Message m = PooledLambda.obtainMessage(
5640 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5641 proc.mUserId);
5642 mH.sendMessage(m);
5643 }
5644
5645 private void cancelHeavyWeightProcessNotification(int userId) {
5646 final INotificationManager inm = NotificationManager.getService();
5647 if (inm == null) {
5648 return;
5649 }
5650 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005651 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005652 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5653 } catch (RuntimeException e) {
5654 Slog.w(TAG, "Error canceling notification for service", e);
5655 } catch (RemoteException e) {
5656 }
5657
5658 }
5659
5660 private void postHeavyWeightProcessNotification(
5661 WindowProcessController proc, Intent intent, int userId) {
5662 if (proc == null) {
5663 return;
5664 }
5665
5666 final INotificationManager inm = NotificationManager.getService();
5667 if (inm == null) {
5668 return;
5669 }
5670
5671 try {
5672 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5673 String text = mContext.getString(R.string.heavy_weight_notification,
5674 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5675 Notification notification =
5676 new Notification.Builder(context,
5677 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5678 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5679 .setWhen(0)
5680 .setOngoing(true)
5681 .setTicker(text)
5682 .setColor(mContext.getColor(
5683 com.android.internal.R.color.system_notification_accent_color))
5684 .setContentTitle(text)
5685 .setContentText(
5686 mContext.getText(R.string.heavy_weight_notification_detail))
5687 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5688 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5689 new UserHandle(userId)))
5690 .build();
5691 try {
5692 inm.enqueueNotificationWithTag("android", "android", null,
5693 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5694 } catch (RuntimeException e) {
5695 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5696 } catch (RemoteException e) {
5697 }
5698 } catch (PackageManager.NameNotFoundException e) {
5699 Slog.w(TAG, "Unable to create context for heavy notification", e);
5700 }
5701
5702 }
5703
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005704 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5705 IBinder token, String resultWho, int requestCode, Intent[] intents,
5706 String[] resolvedTypes, int flags, Bundle bOptions) {
5707
5708 ActivityRecord activity = null;
5709 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5710 activity = ActivityRecord.isInStackLocked(token);
5711 if (activity == null) {
5712 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5713 return null;
5714 }
5715 if (activity.finishing) {
5716 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5717 return null;
5718 }
5719 }
5720
5721 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5722 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5723 bOptions);
5724 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5725 if (noCreate) {
5726 return rec;
5727 }
5728 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5729 if (activity.pendingResults == null) {
5730 activity.pendingResults = new HashSet<>();
5731 }
5732 activity.pendingResults.add(rec.ref);
5733 }
5734 return rec;
5735 }
5736
Andrii Kulian52d255c2018-07-13 11:32:19 -07005737 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005738 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005739 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005740 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5741 mCurAppTimeTracker.start(resumedActivity.packageName);
5742 }
5743 }
5744
5745 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5746 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005747 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005748 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5749 }
5750 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005751 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005752 constructResumedTraceName(resumed.packageName), 0);
5753 }
5754 mTracedResumedActivity = resumed;
5755 }
5756
5757 private String constructResumedTraceName(String packageName) {
5758 return "focused app: " + packageName;
5759 }
5760
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005761 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005762 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005763 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005764 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005765 // mainStack is null during startup.
5766 if (mainStack != null) {
5767 if (changes != 0 && starting == null) {
5768 // If the configuration changed, and the caller is not already
5769 // in the process of starting an activity, then find the top
5770 // activity to check if its configuration needs to change.
5771 starting = mainStack.topRunningActivityLocked();
5772 }
5773
5774 if (starting != null) {
5775 kept = starting.ensureActivityConfiguration(changes,
5776 false /* preserveWindow */);
5777 // And we need to make sure at this point that all other activities
5778 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005779 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005780 !PRESERVE_WINDOWS);
5781 }
5782 }
5783
5784 return kept;
5785 }
5786
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005787 void scheduleAppGcsLocked() {
5788 mH.post(() -> mAmInternal.scheduleAppGcs());
5789 }
5790
Wale Ogunwale53783742018-09-16 10:21:51 -07005791 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5792 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5793 }
5794
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005795 /**
5796 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5797 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5798 * on demand.
5799 */
5800 IPackageManager getPackageManager() {
5801 return AppGlobals.getPackageManager();
5802 }
5803
5804 PackageManagerInternal getPackageManagerInternalLocked() {
5805 if (mPmInternal == null) {
5806 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5807 }
5808 return mPmInternal;
5809 }
5810
Hai Zhangf4da9be2019-05-01 13:46:06 +08005811 PermissionPolicyInternal getPermissionPolicyInternal() {
5812 if (mPermissionPolicyInternal == null) {
5813 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5814 }
5815 return mPermissionPolicyInternal;
5816 }
5817
Wale Ogunwale008163e2018-07-23 23:11:08 -07005818 AppWarnings getAppWarningsLocked() {
5819 return mAppWarnings;
5820 }
5821
Wale Ogunwale214f3482018-10-04 11:00:47 -07005822 Intent getHomeIntent() {
5823 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5824 intent.setComponent(mTopComponent);
5825 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5826 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5827 intent.addCategory(Intent.CATEGORY_HOME);
5828 }
5829 return intent;
5830 }
5831
Chilun2ef71f72018-11-16 17:57:15 +08005832 /**
5833 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5834 * activities.
5835 *
5836 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5837 * component defined in config_secondaryHomeComponent.
5838 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5839 */
5840 Intent getSecondaryHomeIntent(String preferredPackage) {
5841 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005842 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5843 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5844 if (preferredPackage == null || useSystemProvidedLauncher) {
5845 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005846 final String secondaryHomeComponent = mContext.getResources().getString(
5847 com.android.internal.R.string.config_secondaryHomeComponent);
5848 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5849 } else {
5850 intent.setPackage(preferredPackage);
5851 }
5852 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5853 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5854 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5855 }
5856 return intent;
5857 }
5858
Wale Ogunwale214f3482018-10-04 11:00:47 -07005859 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5860 if (info == null) return null;
5861 ApplicationInfo newInfo = new ApplicationInfo(info);
5862 newInfo.initForUser(userId);
5863 return newInfo;
5864 }
5865
Wale Ogunwale9c103022018-10-18 07:44:54 -07005866 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005867 if (uid == SYSTEM_UID) {
5868 // The system gets to run in any process. If there are multiple processes with the same
5869 // uid, just pick the first (this should never happen).
5870 final SparseArray<WindowProcessController> procs =
5871 mProcessNames.getMap().get(processName);
5872 if (procs == null) return null;
5873 final int procCount = procs.size();
5874 for (int i = 0; i < procCount; i++) {
5875 final int procUid = procs.keyAt(i);
5876 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5877 // Don't use an app process or different user process for system component.
5878 continue;
5879 }
5880 return procs.valueAt(i);
5881 }
5882 }
5883
5884 return mProcessNames.get(processName, uid);
5885 }
5886
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005887 WindowProcessController getProcessController(IApplicationThread thread) {
5888 if (thread == null) {
5889 return null;
5890 }
5891
5892 final IBinder threadBinder = thread.asBinder();
5893 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5894 for (int i = pmap.size()-1; i >= 0; i--) {
5895 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5896 for (int j = procs.size() - 1; j >= 0; j--) {
5897 final WindowProcessController proc = procs.valueAt(j);
5898 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5899 return proc;
5900 }
5901 }
5902 }
5903
5904 return null;
5905 }
5906
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005907 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005908 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005909 if (proc == null) return null;
5910 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5911 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005912 }
5913 return null;
5914 }
5915
Riddle Hsua0536432019-02-16 00:38:59 +08005916 int getUidState(int uid) {
5917 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005918 }
5919
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005920 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005921 // A uid is considered to be foreground if it has a visible non-toast window.
5922 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005923 }
5924
Ricky Wai96f5c352019-04-10 18:40:17 +01005925 boolean isDeviceOwner(int uid) {
5926 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005927 }
5928
Ricky Wai96f5c352019-04-10 18:40:17 +01005929 void setDeviceOwnerUid(int uid) {
5930 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005931 }
5932
Wale Ogunwale9de19442018-10-18 19:05:03 -07005933 /**
5934 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5935 * the whitelist
5936 */
5937 String getPendingTempWhitelistTagForUidLocked(int uid) {
5938 return mPendingTempWhitelist.get(uid);
5939 }
5940
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005941 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5942 if (true || Build.IS_USER) {
5943 return;
5944 }
5945
5946 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5947 StrictMode.allowThreadDiskWrites();
5948 try {
5949 File tracesDir = new File("/data/anr");
5950 File tracesFile = null;
5951 try {
5952 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5953
5954 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005955 String timeString =
5956 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5957 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005958 sb.append(": ");
5959 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5960 sb.append(" since ");
5961 sb.append(msg);
5962 FileOutputStream fos = new FileOutputStream(tracesFile);
5963 fos.write(sb.toString().getBytes());
5964 if (app == null) {
5965 fos.write("\n*** No application process!".getBytes());
5966 }
5967 fos.close();
5968 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5969 } catch (IOException e) {
5970 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5971 return;
5972 }
5973
5974 if (app != null && app.getPid() > 0) {
5975 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5976 firstPids.add(app.getPid());
5977 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5978 }
5979
5980 File lastTracesFile = null;
5981 File curTracesFile = null;
5982 for (int i=9; i>=0; i--) {
5983 String name = String.format(Locale.US, "slow%02d.txt", i);
5984 curTracesFile = new File(tracesDir, name);
5985 if (curTracesFile.exists()) {
5986 if (lastTracesFile != null) {
5987 curTracesFile.renameTo(lastTracesFile);
5988 } else {
5989 curTracesFile.delete();
5990 }
5991 }
5992 lastTracesFile = curTracesFile;
5993 }
5994 tracesFile.renameTo(curTracesFile);
5995 } finally {
5996 StrictMode.setThreadPolicy(oldPolicy);
5997 }
5998 }
5999
Michal Karpinskida34cd42019-04-02 19:46:52 +01006000 boolean isAssociatedCompanionApp(int userId, int uid) {
6001 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6002 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006003 return false;
6004 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006005 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006006 }
6007
Issei Suzuki734bc942019-06-05 13:59:52 +02006008 void notifySingleTaskDisplayEmpty(int displayId) {
6009 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6010 }
6011
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006012 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006013 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006014
6015
Wale Ogunwale98875612018-10-12 07:53:02 -07006016 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6017 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006018
Riddle Hsud93a6c42018-11-29 21:50:06 +08006019 H(Looper looper) {
6020 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006021 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006022
6023 @Override
6024 public void handleMessage(Message msg) {
6025 switch (msg.what) {
6026 case REPORT_TIME_TRACKER_MSG: {
6027 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6028 tracker.deliverResult(mContext);
6029 } break;
6030 }
6031 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006032 }
6033
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006034 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006035 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006036
6037 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006038 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006039 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006040
6041 @Override
6042 public void handleMessage(Message msg) {
6043 switch (msg.what) {
6044 case DISMISS_DIALOG_UI_MSG: {
6045 final Dialog d = (Dialog) msg.obj;
6046 d.dismiss();
6047 break;
6048 }
6049 }
6050 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006051 }
6052
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 final class LocalService extends ActivityTaskManagerInternal {
6054 @Override
6055 public SleepToken acquireSleepToken(String tag, int displayId) {
6056 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006057 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006058 }
6059
6060 @Override
6061 public ComponentName getHomeActivityForUser(int userId) {
6062 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006063 final ActivityRecord homeActivity =
6064 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006065 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 }
6067 }
6068
6069 @Override
6070 public void onLocalVoiceInteractionStarted(IBinder activity,
6071 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6072 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006073 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006074 }
6075 }
6076
6077 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006078 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006079 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006080 synchronized (mGlobalLock) {
6081 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006082 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006083 }
6084 }
6085
6086 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006087 public void notifySingleTaskDisplayDrawn(int displayId) {
6088 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6089 }
6090
6091 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006092 public void notifyAppTransitionFinished() {
6093 synchronized (mGlobalLock) {
6094 mStackSupervisor.notifyAppTransitionDone();
6095 }
6096 }
6097
6098 @Override
6099 public void notifyAppTransitionCancelled() {
6100 synchronized (mGlobalLock) {
6101 mStackSupervisor.notifyAppTransitionDone();
6102 }
6103 }
6104
6105 @Override
6106 public List<IBinder> getTopVisibleActivities() {
6107 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006108 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006109 }
6110 }
6111
6112 @Override
6113 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6114 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006115 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006116 }
6117 }
6118
6119 @Override
6120 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6121 Bundle bOptions) {
6122 Preconditions.checkNotNull(intents, "intents");
6123 final String[] resolvedTypes = new String[intents.length];
6124
6125 // UID of the package on user userId.
6126 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6127 // packageUid may not be initialized.
6128 int packageUid = 0;
6129 final long ident = Binder.clearCallingIdentity();
6130
6131 try {
6132 for (int i = 0; i < intents.length; i++) {
6133 resolvedTypes[i] =
6134 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6135 }
6136
6137 packageUid = AppGlobals.getPackageManager().getPackageUid(
6138 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6139 } catch (RemoteException e) {
6140 // Shouldn't happen.
6141 } finally {
6142 Binder.restoreCallingIdentity(ident);
6143 }
6144
Riddle Hsu591bf612019-02-14 17:55:31 +08006145 return getActivityStartController().startActivitiesInPackage(
6146 packageUid, packageName,
6147 intents, resolvedTypes, null /* resultTo */,
6148 SafeActivityOptions.fromBundle(bOptions), userId,
6149 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6150 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006151 }
6152
6153 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006154 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6155 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6156 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6157 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006158 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006159 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006160 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6161 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6162 userId, validateIncomingUser, originatingPendingIntent,
6163 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006164 }
6165 }
6166
6167 @Override
6168 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6169 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6170 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006171 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006172 PendingIntentRecord originatingPendingIntent,
6173 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006174 synchronized (mGlobalLock) {
6175 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6176 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6177 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006178 validateIncomingUser, originatingPendingIntent,
6179 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006180 }
6181 }
6182
6183 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006184 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6185 Intent intent, Bundle options, int userId) {
6186 return ActivityTaskManagerService.this.startActivityAsUser(
6187 caller, callerPacakge, intent,
6188 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6189 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6190 false /*validateIncomingUser*/);
6191 }
6192
6193 @Override
lumark588a3e82018-07-20 18:53:54 +08006194 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006195 synchronized (mGlobalLock) {
6196
6197 // We might change the visibilities here, so prepare an empty app transition which
6198 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006199 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006200 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006201 if (activityDisplay == null) {
6202 return;
6203 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006204 final DisplayContent dc = activityDisplay.mDisplayContent;
6205 final boolean wasTransitionSet =
6206 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006208 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006209 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006210 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211
6212 // If there was a transition set already we don't want to interfere with it as we
6213 // might be starting it too early.
6214 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006215 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006216 }
6217 }
6218 if (callback != null) {
6219 callback.run();
6220 }
6221 }
6222
6223 @Override
6224 public void notifyKeyguardTrustedChanged() {
6225 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006226 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006227 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006228 }
6229 }
6230 }
6231
6232 /**
6233 * Called after virtual display Id is updated by
6234 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6235 * {@param vrVr2dDisplayId}.
6236 */
6237 @Override
6238 public void setVr2dDisplayId(int vr2dDisplayId) {
6239 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6240 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006241 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 }
6243 }
6244
6245 @Override
6246 public void setFocusedActivity(IBinder token) {
6247 synchronized (mGlobalLock) {
6248 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6249 if (r == null) {
6250 throw new IllegalArgumentException(
6251 "setFocusedActivity: No activity record matching token=" + token);
6252 }
Louis Chang19443452018-10-09 12:10:21 +08006253 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006254 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255 }
6256 }
6257 }
6258
6259 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006261 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006262 }
6263
6264 @Override
6265 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006266 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006267 }
6268
6269 @Override
6270 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006271 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 }
6273
6274 @Override
6275 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6276 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6277 }
6278
6279 @Override
6280 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006281 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006283
6284 @Override
6285 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6286 synchronized (mGlobalLock) {
6287 mActiveVoiceInteractionServiceComponent = component;
6288 }
6289 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006290
6291 @Override
6292 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6293 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6294 return;
6295 }
6296 synchronized (mGlobalLock) {
6297 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6298 if (types == null) {
6299 if (uid < 0) {
6300 return;
6301 }
6302 types = new ArrayMap<>();
6303 mAllowAppSwitchUids.put(userId, types);
6304 }
6305 if (uid < 0) {
6306 types.remove(type);
6307 } else {
6308 types.put(type, uid);
6309 }
6310 }
6311 }
6312
6313 @Override
6314 public void onUserStopped(int userId) {
6315 synchronized (mGlobalLock) {
6316 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6317 mAllowAppSwitchUids.remove(userId);
6318 }
6319 }
6320
6321 @Override
6322 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6323 synchronized (mGlobalLock) {
6324 return ActivityTaskManagerService.this.isGetTasksAllowed(
6325 caller, callingPid, callingUid);
6326 }
6327 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006328
Riddle Hsua0536432019-02-16 00:38:59 +08006329 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006330 @Override
6331 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006332 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006333 mProcessNames.put(proc.mName, proc.mUid, proc);
6334 }
6335 }
6336
Riddle Hsua0536432019-02-16 00:38:59 +08006337 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006338 @Override
6339 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006340 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006341 mProcessNames.remove(name, uid);
6342 }
6343 }
6344
Riddle Hsua0536432019-02-16 00:38:59 +08006345 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006346 @Override
6347 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006348 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006349 if (proc == mHomeProcess) {
6350 mHomeProcess = null;
6351 }
6352 if (proc == mPreviousProcess) {
6353 mPreviousProcess = null;
6354 }
6355 }
6356 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006357
Riddle Hsua0536432019-02-16 00:38:59 +08006358 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006359 @Override
6360 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006361 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006362 return mTopProcessState;
6363 }
6364 }
6365
Riddle Hsua0536432019-02-16 00:38:59 +08006366 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006367 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006368 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006369 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006370 return proc == mHeavyWeightProcess;
6371 }
6372 }
6373
Riddle Hsua0536432019-02-16 00:38:59 +08006374 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006375 @Override
6376 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006377 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006378 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6379 }
6380 }
6381
6382 @Override
6383 public void finishHeavyWeightApp() {
6384 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006385 if (mHeavyWeightProcess != null) {
6386 mHeavyWeightProcess.finishActivities();
6387 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006388 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6389 mHeavyWeightProcess);
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006394 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006395 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006397 return isSleepingLocked();
6398 }
6399 }
6400
6401 @Override
6402 public boolean isShuttingDown() {
6403 synchronized (mGlobalLock) {
6404 return mShuttingDown;
6405 }
6406 }
6407
6408 @Override
6409 public boolean shuttingDown(boolean booted, int timeout) {
6410 synchronized (mGlobalLock) {
6411 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006412 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006413 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006414 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006415 return mStackSupervisor.shutdownLocked(timeout);
6416 }
6417 }
6418
6419 @Override
6420 public void enableScreenAfterBoot(boolean booted) {
6421 synchronized (mGlobalLock) {
6422 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6423 SystemClock.uptimeMillis());
6424 mWindowManager.enableScreenAfterBoot();
6425 updateEventDispatchingLocked(booted);
6426 }
6427 }
6428
6429 @Override
6430 public boolean showStrictModeViolationDialog() {
6431 synchronized (mGlobalLock) {
6432 return mShowDialogs && !mSleeping && !mShuttingDown;
6433 }
6434 }
6435
6436 @Override
6437 public void showSystemReadyErrorDialogsIfNeeded() {
6438 synchronized (mGlobalLock) {
6439 try {
6440 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6441 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6442 + " data partition or your device will be unstable.");
6443 mUiHandler.post(() -> {
6444 if (mShowDialogs) {
6445 AlertDialog d = new BaseErrorDialog(mUiContext);
6446 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6447 d.setCancelable(false);
6448 d.setTitle(mUiContext.getText(R.string.android_system_label));
6449 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6450 d.setButton(DialogInterface.BUTTON_POSITIVE,
6451 mUiContext.getText(R.string.ok),
6452 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6453 d.show();
6454 }
6455 });
6456 }
6457 } catch (RemoteException e) {
6458 }
6459
6460 if (!Build.isBuildConsistent()) {
6461 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6462 mUiHandler.post(() -> {
6463 if (mShowDialogs) {
6464 AlertDialog d = new BaseErrorDialog(mUiContext);
6465 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6466 d.setCancelable(false);
6467 d.setTitle(mUiContext.getText(R.string.android_system_label));
6468 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6469 d.setButton(DialogInterface.BUTTON_POSITIVE,
6470 mUiContext.getText(R.string.ok),
6471 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6472 d.show();
6473 }
6474 });
6475 }
6476 }
6477 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006478
6479 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006480 public void onProcessMapped(int pid, WindowProcessController proc) {
6481 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006482 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006483 }
6484 }
6485
6486 @Override
6487 public void onProcessUnMapped(int pid) {
6488 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006489 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006490 }
6491 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006492
6493 @Override
6494 public void onPackageDataCleared(String name) {
6495 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006496 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006497 mAppWarnings.onPackageDataCleared(name);
6498 }
6499 }
6500
6501 @Override
6502 public void onPackageUninstalled(String name) {
6503 synchronized (mGlobalLock) {
6504 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006505 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006506 }
6507 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006508
6509 @Override
6510 public void onPackageAdded(String name, boolean replacing) {
6511 synchronized (mGlobalLock) {
6512 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6513 }
6514 }
6515
6516 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006517 public void onPackageReplaced(ApplicationInfo aInfo) {
6518 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006519 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006520 }
6521 }
6522
6523 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006524 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6525 synchronized (mGlobalLock) {
6526 return compatibilityInfoForPackageLocked(ai);
6527 }
6528 }
6529
Yunfan Chen75157d72018-07-27 14:47:21 +09006530 /**
6531 * Set the corresponding display information for the process global configuration. To be
6532 * called when we need to show IME on a different display.
6533 *
6534 * @param pid The process id associated with the IME window.
6535 * @param displayId The ID of the display showing the IME.
6536 */
6537 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006538 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006539 // Don't update process-level configuration for Multi-Client IME process since other
6540 // IMEs on other displays will also receive this configuration change due to IME
6541 // services use the same application config/context.
6542 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006543
Yunfan Chen75157d72018-07-27 14:47:21 +09006544 if (pid == MY_PID || pid < 0) {
6545 if (DEBUG_CONFIGURATION) {
6546 Slog.w(TAG,
6547 "Trying to update display configuration for system/invalid process.");
6548 }
6549 return;
6550 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006551 synchronized (mGlobalLock) {
6552 final ActivityDisplay activityDisplay =
6553 mRootActivityContainer.getActivityDisplay(displayId);
6554 if (activityDisplay == null) {
6555 // Call might come when display is not yet added or has been removed.
6556 if (DEBUG_CONFIGURATION) {
6557 Slog.w(TAG, "Trying to update display configuration for non-existing "
6558 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006559 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006560 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006561 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006562 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006563 if (process == null) {
6564 if (DEBUG_CONFIGURATION) {
6565 Slog.w(TAG, "Trying to update display configuration for invalid "
6566 + "process, pid=" + pid);
6567 }
6568 return;
6569 }
lumarkddc77fb2019-06-27 22:22:23 +08006570 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006571 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6572 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006573 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006574
6575 @Override
6576 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006577 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006578 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006579 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6580 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006581 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006582 }
6583 }
6584 }
6585
6586 @Override
6587 public void clearPendingResultForActivity(IBinder activityToken,
6588 WeakReference<PendingIntentRecord> pir) {
6589 synchronized (mGlobalLock) {
6590 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6591 if (r != null && r.pendingResults != null) {
6592 r.pendingResults.remove(pir);
6593 }
6594 }
6595 }
6596
6597 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006598 public ActivityTokens getTopActivityForTask(int taskId) {
6599 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006600 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6601 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006602 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6603 + " Requested task not found");
6604 return null;
6605 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006606 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006607 if (activity == null) {
6608 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6609 + " Requested activity not found");
6610 return null;
6611 }
6612 if (!activity.attachedToProcess()) {
6613 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6614 + activity);
6615 return null;
6616 }
6617 return new ActivityTokens(activity.appToken, activity.assistToken,
6618 activity.app.getThread());
6619 }
6620 }
6621
6622 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006623 public IIntentSender getIntentSender(int type, String packageName,
6624 int callingUid, int userId, IBinder token, String resultWho,
6625 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6626 Bundle bOptions) {
6627 synchronized (mGlobalLock) {
6628 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6629 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6630 }
6631 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006632
6633 @Override
6634 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6635 synchronized (mGlobalLock) {
6636 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6637 if (r == null) {
6638 return null;
6639 }
6640 if (r.mServiceConnectionsHolder == null) {
6641 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6642 ActivityTaskManagerService.this, r);
6643 }
6644
6645 return r.mServiceConnectionsHolder;
6646 }
6647 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006648
6649 @Override
6650 public Intent getHomeIntent() {
6651 synchronized (mGlobalLock) {
6652 return ActivityTaskManagerService.this.getHomeIntent();
6653 }
6654 }
6655
6656 @Override
6657 public boolean startHomeActivity(int userId, String reason) {
6658 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006659 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006660 }
6661 }
6662
6663 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006664 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006665 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006666 synchronized (mGlobalLock) {
6667 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006668 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006669 }
Chilun8b1f1be2019-03-13 17:14:36 +08006670 }
6671
6672 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006673 public boolean startHomeOnAllDisplays(int userId, String reason) {
6674 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006675 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006676 }
6677 }
6678
Riddle Hsua0536432019-02-16 00:38:59 +08006679 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006680 @Override
6681 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006682 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006683 if (mFactoryTest == FACTORY_TEST_OFF) {
6684 return false;
6685 }
6686 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6687 && wpc.mName.equals(mTopComponent.getPackageName())) {
6688 return true;
6689 }
6690 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6691 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6692 }
6693 }
6694
6695 @Override
6696 public void updateTopComponentForFactoryTest() {
6697 synchronized (mGlobalLock) {
6698 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6699 return;
6700 }
6701 final ResolveInfo ri = mContext.getPackageManager()
6702 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6703 final CharSequence errorMsg;
6704 if (ri != null) {
6705 final ActivityInfo ai = ri.activityInfo;
6706 final ApplicationInfo app = ai.applicationInfo;
6707 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6708 mTopAction = Intent.ACTION_FACTORY_TEST;
6709 mTopData = null;
6710 mTopComponent = new ComponentName(app.packageName, ai.name);
6711 errorMsg = null;
6712 } else {
6713 errorMsg = mContext.getResources().getText(
6714 com.android.internal.R.string.factorytest_not_system);
6715 }
6716 } else {
6717 errorMsg = mContext.getResources().getText(
6718 com.android.internal.R.string.factorytest_no_action);
6719 }
6720 if (errorMsg == null) {
6721 return;
6722 }
6723
6724 mTopAction = null;
6725 mTopData = null;
6726 mTopComponent = null;
6727 mUiHandler.post(() -> {
6728 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6729 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006730 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006731 });
6732 }
6733 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734
Riddle Hsua0536432019-02-16 00:38:59 +08006735 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006736 @Override
6737 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6738 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006739 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006741 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742
6743 wpc.clearRecentTasks();
6744 wpc.clearActivities();
6745
6746 if (wpc.isInstrumenting()) {
6747 finishInstrumentationCallback.run();
6748 }
6749
Jorim Jaggid0752812018-10-16 16:07:20 +02006750 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006751 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006752 try {
6753 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6754 // If there was nothing to resume, and we are not already restarting
6755 // this process, but there is a visible activity that is hosted by the
6756 // process...then make sure all visible activities are running, taking
6757 // care of restarting this process.
6758 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6759 !PRESERVE_WINDOWS);
6760 }
6761 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006762 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006764 }
6765 }
6766 }
6767
6768 @Override
6769 public void closeSystemDialogs(String reason) {
6770 enforceNotIsolatedCaller("closeSystemDialogs");
6771
6772 final int pid = Binder.getCallingPid();
6773 final int uid = Binder.getCallingUid();
6774 final long origId = Binder.clearCallingIdentity();
6775 try {
6776 synchronized (mGlobalLock) {
6777 // Only allow this from foreground processes, so that background
6778 // applications can't abuse it to prevent system UI from being shown.
6779 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006780 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006781 if (!proc.isPerceptible()) {
6782 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6783 + " from background process " + proc);
6784 return;
6785 }
6786 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 mWindowManager.closeSystemDialogs(reason);
6788
Wale Ogunwaled32da472018-11-16 07:19:28 -08006789 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006791 // Call into AM outside the synchronized block.
6792 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006793 } finally {
6794 Binder.restoreCallingIdentity(origId);
6795 }
6796 }
6797
6798 @Override
6799 public void cleanupDisabledPackageComponents(
6800 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6801 synchronized (mGlobalLock) {
6802 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006803 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006805 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 mStackSupervisor.scheduleIdleLocked();
6807 }
6808
6809 // Clean-up disabled tasks
6810 getRecentTasks().cleanupDisabledPackageTasksLocked(
6811 packageName, disabledClasses, userId);
6812 }
6813 }
6814
6815 @Override
6816 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6817 int userId) {
6818 synchronized (mGlobalLock) {
6819
6820 boolean didSomething =
6821 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006822 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 null, doit, evenPersistent, userId);
6824 return didSomething;
6825 }
6826 }
6827
6828 @Override
6829 public void resumeTopActivities(boolean scheduleIdle) {
6830 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006831 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 if (scheduleIdle) {
6833 mStackSupervisor.scheduleIdleLocked();
6834 }
6835 }
6836 }
6837
Riddle Hsua0536432019-02-16 00:38:59 +08006838 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839 @Override
6840 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006841 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6843 }
6844 }
6845
Riddle Hsua0536432019-02-16 00:38:59 +08006846 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006847 @Override
6848 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006849 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006850 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6851 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6852 }
6853 try {
6854 return mRootActivityContainer.attachApplication(wpc);
6855 } finally {
6856 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6857 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 }
6859 }
6860
6861 @Override
6862 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6863 try {
6864 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6865 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6866 }
6867 } catch (RemoteException ex) {
6868 throw new SecurityException("Fail to check is caller a privileged app", ex);
6869 }
6870
6871 synchronized (mGlobalLock) {
6872 final long ident = Binder.clearCallingIdentity();
6873 try {
6874 if (mAmInternal.shouldConfirmCredentials(userId)) {
6875 if (mKeyguardController.isKeyguardLocked()) {
6876 // Showing launcher to avoid user entering credential twice.
6877 startHomeActivity(currentUserId, "notifyLockedProfile");
6878 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006879 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 }
6881 } finally {
6882 Binder.restoreCallingIdentity(ident);
6883 }
6884 }
6885 }
6886
6887 @Override
6888 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6889 mAmInternal.enforceCallingPermission(
6890 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6891
6892 synchronized (mGlobalLock) {
6893 final long ident = Binder.clearCallingIdentity();
6894 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006895 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6896 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006897 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6899 UserHandle.CURRENT);
6900 } finally {
6901 Binder.restoreCallingIdentity(ident);
6902 }
6903 }
6904 }
6905
6906 @Override
6907 public void writeActivitiesToProto(ProtoOutputStream proto) {
6908 synchronized (mGlobalLock) {
6909 // The output proto of "activity --proto activities"
6910 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006911 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006912 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6913 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 }
6915 }
6916
6917 @Override
6918 public void saveANRState(String reason) {
6919 synchronized (mGlobalLock) {
6920 final StringWriter sw = new StringWriter();
6921 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6922 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6923 if (reason != null) {
6924 pw.println(" Reason: " + reason);
6925 }
6926 pw.println();
6927 getActivityStartController().dump(pw, " ", null);
6928 pw.println();
6929 pw.println("-------------------------------------------------------------------------------");
6930 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6931 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6932 "" /* header */);
6933 pw.println();
6934 pw.close();
6935
6936 mLastANRState = sw.toString();
6937 }
6938 }
6939
6940 @Override
6941 public void clearSavedANRState() {
6942 synchronized (mGlobalLock) {
6943 mLastANRState = null;
6944 }
6945 }
6946
6947 @Override
6948 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6949 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6950 synchronized (mGlobalLock) {
6951 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6952 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6953 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6954 dumpLastANRLocked(pw);
6955 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6956 dumpLastANRTracesLocked(pw);
6957 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6958 dumpActivityStarterLocked(pw, dumpPackage);
6959 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6960 dumpActivityContainersLocked(pw);
6961 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6962 if (getRecentTasks() != null) {
6963 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6964 }
6965 }
6966 }
6967 }
6968
6969 @Override
6970 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6971 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6972 int wakefulness) {
6973 synchronized (mGlobalLock) {
6974 if (mHomeProcess != null && (dumpPackage == null
6975 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6976 if (needSep) {
6977 pw.println();
6978 needSep = false;
6979 }
6980 pw.println(" mHomeProcess: " + mHomeProcess);
6981 }
6982 if (mPreviousProcess != null && (dumpPackage == null
6983 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6984 if (needSep) {
6985 pw.println();
6986 needSep = false;
6987 }
6988 pw.println(" mPreviousProcess: " + mPreviousProcess);
6989 }
6990 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6991 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6992 StringBuilder sb = new StringBuilder(128);
6993 sb.append(" mPreviousProcessVisibleTime: ");
6994 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6995 pw.println(sb);
6996 }
6997 if (mHeavyWeightProcess != null && (dumpPackage == null
6998 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6999 if (needSep) {
7000 pw.println();
7001 needSep = false;
7002 }
7003 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7004 }
7005 if (dumpPackage == null) {
7006 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007007 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007008 }
7009 if (dumpAll) {
7010 if (dumpPackage == null) {
7011 pw.println(" mConfigWillChange: "
7012 + getTopDisplayFocusedStack().mConfigWillChange);
7013 }
7014 if (mCompatModePackages.getPackages().size() > 0) {
7015 boolean printed = false;
7016 for (Map.Entry<String, Integer> entry
7017 : mCompatModePackages.getPackages().entrySet()) {
7018 String pkg = entry.getKey();
7019 int mode = entry.getValue();
7020 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7021 continue;
7022 }
7023 if (!printed) {
7024 pw.println(" mScreenCompatPackages:");
7025 printed = true;
7026 }
7027 pw.println(" " + pkg + ": " + mode);
7028 }
7029 }
7030 }
7031
7032 if (dumpPackage == null) {
7033 pw.println(" mWakefulness="
7034 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007035 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007036 if (mRunningVoice != null) {
7037 pw.println(" mRunningVoice=" + mRunningVoice);
7038 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7039 }
7040 pw.println(" mSleeping=" + mSleeping);
7041 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7042 pw.println(" mVrController=" + mVrController);
7043 }
7044 if (mCurAppTimeTracker != null) {
7045 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7046 }
7047 if (mAllowAppSwitchUids.size() > 0) {
7048 boolean printed = false;
7049 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7050 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7051 for (int j = 0; j < types.size(); j++) {
7052 if (dumpPackage == null ||
7053 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7054 if (needSep) {
7055 pw.println();
7056 needSep = false;
7057 }
7058 if (!printed) {
7059 pw.println(" mAllowAppSwitchUids:");
7060 printed = true;
7061 }
7062 pw.print(" User ");
7063 pw.print(mAllowAppSwitchUids.keyAt(i));
7064 pw.print(": Type ");
7065 pw.print(types.keyAt(j));
7066 pw.print(" = ");
7067 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7068 pw.println();
7069 }
7070 }
7071 }
7072 }
7073 if (dumpPackage == null) {
7074 if (mController != null) {
7075 pw.println(" mController=" + mController
7076 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7077 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007078 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7079 pw.println(" mLaunchingActivityWakeLock="
7080 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007081 }
7082
7083 return needSep;
7084 }
7085 }
7086
7087 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007088 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7089 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 synchronized (mGlobalLock) {
7091 if (dumpPackage == null) {
7092 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7093 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007094 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7095 if (mRunningVoice != null) {
7096 final long vrToken = proto.start(
7097 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7098 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7099 mRunningVoice.toString());
7100 mVoiceWakeLock.writeToProto(
7101 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7102 proto.end(vrToken);
7103 }
7104 mVrController.writeToProto(proto,
7105 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 if (mController != null) {
7107 final long token = proto.start(CONTROLLER);
7108 proto.write(CONTROLLER, mController.toString());
7109 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7110 proto.end(token);
7111 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007112 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7113 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7114 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 }
7116
7117 if (mHomeProcess != null && (dumpPackage == null
7118 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007119 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 }
7121
7122 if (mPreviousProcess != null && (dumpPackage == null
7123 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007124 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007125 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7126 }
7127
7128 if (mHeavyWeightProcess != null && (dumpPackage == null
7129 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007130 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 }
7132
7133 for (Map.Entry<String, Integer> entry
7134 : mCompatModePackages.getPackages().entrySet()) {
7135 String pkg = entry.getKey();
7136 int mode = entry.getValue();
7137 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7138 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7139 proto.write(PACKAGE, pkg);
7140 proto.write(MODE, mode);
7141 proto.end(compatToken);
7142 }
7143 }
7144
7145 if (mCurAppTimeTracker != null) {
7146 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7147 }
7148
7149 }
7150 }
7151
7152 @Override
7153 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7154 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7155 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007156 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7157 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007158 }
7159
7160 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007161 public void dumpForOom(PrintWriter pw) {
7162 synchronized (mGlobalLock) {
7163 pw.println(" mHomeProcess: " + mHomeProcess);
7164 pw.println(" mPreviousProcess: " + mPreviousProcess);
7165 if (mHeavyWeightProcess != null) {
7166 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7167 }
7168 }
7169 }
7170
7171 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007172 public boolean canGcNow() {
7173 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007174 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007175 }
7176 }
7177
Riddle Hsua0536432019-02-16 00:38:59 +08007178 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 @Override
7180 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007181 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007182 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 return top != null ? top.app : null;
7184 }
7185 }
7186
Riddle Hsua0536432019-02-16 00:38:59 +08007187 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 @Override
7189 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007190 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007191 if (mRootActivityContainer != null) {
7192 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007193 }
7194 }
7195 }
7196
7197 @Override
7198 public void scheduleDestroyAllActivities(String reason) {
7199 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007200 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007201 }
7202 }
7203
7204 @Override
7205 public void removeUser(int userId) {
7206 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007207 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007208 }
7209 }
7210
7211 @Override
7212 public boolean switchUser(int userId, UserState userState) {
7213 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007214 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 }
7216 }
7217
7218 @Override
7219 public void onHandleAppCrash(WindowProcessController wpc) {
7220 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007221 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 }
7223 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007224
7225 @Override
7226 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7227 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007228 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007229 }
7230 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007231
Riddle Hsua0536432019-02-16 00:38:59 +08007232 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007233 @Override
7234 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007235 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007236 }
7237
Riddle Hsua0536432019-02-16 00:38:59 +08007238 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007239 @Override
7240 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007241 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007242 }
7243
Riddle Hsua0536432019-02-16 00:38:59 +08007244 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007245 @Override
7246 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007247 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007248 }
7249
Riddle Hsua0536432019-02-16 00:38:59 +08007250 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007251 @Override
7252 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007253 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007254 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007255
7256 @Override
7257 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007258 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007259 mPendingTempWhitelist.put(uid, tag);
7260 }
7261 }
7262
7263 @Override
7264 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007265 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007266 mPendingTempWhitelist.remove(uid);
7267 }
7268 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007269
7270 @Override
7271 public boolean handleAppCrashInActivityController(String processName, int pid,
7272 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7273 Runnable killCrashingAppCallback) {
7274 synchronized (mGlobalLock) {
7275 if (mController == null) {
7276 return false;
7277 }
7278
7279 try {
7280 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7281 stackTrace)) {
7282 killCrashingAppCallback.run();
7283 return true;
7284 }
7285 } catch (RemoteException e) {
7286 mController = null;
7287 Watchdog.getInstance().setActivityController(null);
7288 }
7289 return false;
7290 }
7291 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007292
7293 @Override
7294 public void removeRecentTasksByPackageName(String packageName, int userId) {
7295 synchronized (mGlobalLock) {
7296 mRecentTasks.removeTasksByPackageName(packageName, userId);
7297 }
7298 }
7299
7300 @Override
7301 public void cleanupRecentTasksForUser(int userId) {
7302 synchronized (mGlobalLock) {
7303 mRecentTasks.cleanupLocked(userId);
7304 }
7305 }
7306
7307 @Override
7308 public void loadRecentTasksForUser(int userId) {
7309 synchronized (mGlobalLock) {
7310 mRecentTasks.loadUserRecentsLocked(userId);
7311 }
7312 }
7313
7314 @Override
7315 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7316 synchronized (mGlobalLock) {
7317 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7318 }
7319 }
7320
7321 @Override
7322 public void flushRecentTasks() {
7323 mRecentTasks.flush();
7324 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007325
7326 @Override
7327 public WindowProcessController getHomeProcess() {
7328 synchronized (mGlobalLock) {
7329 return mHomeProcess;
7330 }
7331 }
7332
7333 @Override
7334 public WindowProcessController getPreviousProcess() {
7335 synchronized (mGlobalLock) {
7336 return mPreviousProcess;
7337 }
7338 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007339
7340 @Override
7341 public void clearLockedTasks(String reason) {
7342 synchronized (mGlobalLock) {
7343 getLockTaskController().clearLockedTasks(reason);
7344 }
7345 }
7346
7347 @Override
7348 public void updateUserConfiguration() {
7349 synchronized (mGlobalLock) {
7350 final Configuration configuration = new Configuration(getGlobalConfiguration());
7351 final int currentUserId = mAmInternal.getCurrentUserId();
7352 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7353 configuration, currentUserId, Settings.System.canWrite(mContext));
7354 updateConfigurationLocked(configuration, null /* starting */,
7355 false /* initLocale */, false /* persistent */, currentUserId,
7356 false /* deferResume */);
7357 }
7358 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007359
7360 @Override
7361 public boolean canShowErrorDialogs() {
7362 synchronized (mGlobalLock) {
7363 return mShowDialogs && !mSleeping && !mShuttingDown
7364 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7365 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7366 mAmInternal.getCurrentUserId())
7367 && !(UserManager.isDeviceInDemoMode(mContext)
7368 && mAmInternal.getCurrentUser().isDemo());
7369 }
7370 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007371
7372 @Override
7373 public void setProfileApp(String profileApp) {
7374 synchronized (mGlobalLock) {
7375 mProfileApp = profileApp;
7376 }
7377 }
7378
7379 @Override
7380 public void setProfileProc(WindowProcessController wpc) {
7381 synchronized (mGlobalLock) {
7382 mProfileProc = wpc;
7383 }
7384 }
7385
7386 @Override
7387 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7388 synchronized (mGlobalLock) {
7389 mProfilerInfo = profilerInfo;
7390 }
7391 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007392
7393 @Override
7394 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7395 synchronized (mGlobalLock) {
7396 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7397 }
7398 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007399
7400 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007401 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7402 boolean reducedResolution) {
7403 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7404 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007405 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007406
7407 @Override
7408 public boolean isUidForeground(int uid) {
7409 synchronized (mGlobalLock) {
7410 return ActivityTaskManagerService.this.isUidForeground(uid);
7411 }
7412 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007413
7414 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007415 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007416 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007417 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007418 }
7419 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007420
7421 @Override
7422 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007423 // Translate package names into UIDs
7424 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007425 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007426 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7427 if (uid >= 0) {
7428 result.add(uid);
7429 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007430 }
7431 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007432 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007433 }
7434 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007435 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007436}