blob: 6977a45e32755bbda130cdf6b4b5e92ff65ab220 [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) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002776 return mRootActivityContainer.getAllStackInfos();
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
2797 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002798 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 final long callingUid = Binder.getCallingUid();
2800 final long origId = Binder.clearCallingIdentity();
2801 try {
2802 synchronized (mGlobalLock) {
2803 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002804 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2806 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2807 }
2808 } finally {
2809 Binder.restoreCallingIdentity(origId);
2810 }
2811 }
2812
2813 @Override
2814 public void startLockTaskModeByToken(IBinder token) {
2815 synchronized (mGlobalLock) {
2816 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2817 if (r == null) {
2818 return;
2819 }
Louis Changcdec0802019-11-11 11:45:07 +08002820 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 }
2823
2824 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002825 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002826 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 // This makes inner call to look as if it was initiated by system.
2828 long ident = Binder.clearCallingIdentity();
2829 try {
2830 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002831 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002832 MATCH_TASK_IN_STACKS_ONLY);
2833 if (task == null) {
2834 return;
2835 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836
2837 // When starting lock task mode the stack must be in front and focused
2838 task.getStack().moveToFront("startSystemLockTaskMode");
2839 startLockTaskModeLocked(task, true /* isSystemCaller */);
2840 }
2841 } finally {
2842 Binder.restoreCallingIdentity(ident);
2843 }
2844 }
2845
2846 @Override
2847 public void stopLockTaskModeByToken(IBinder token) {
2848 synchronized (mGlobalLock) {
2849 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2850 if (r == null) {
2851 return;
2852 }
Louis Changcdec0802019-11-11 11:45:07 +08002853 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 }
2855 }
2856
2857 /**
2858 * This API should be called by SystemUI only when user perform certain action to dismiss
2859 * lock task mode. We should only dismiss pinned lock task mode in this case.
2860 */
2861 @Override
2862 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002863 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2865 }
2866
Louis Changcdec0802019-11-11 11:45:07 +08002867 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2869 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2870 return;
2871 }
2872
Wale Ogunwaled32da472018-11-16 07:19:28 -08002873 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 if (stack == null || task != stack.topTask()) {
2875 throw new IllegalArgumentException("Invalid task, not in foreground");
2876 }
2877
2878 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2879 // system or a specific app.
2880 // * System-initiated requests will only start the pinned mode (screen pinning)
2881 // * App-initiated requests
2882 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2883 // - will start the pinned mode, otherwise
2884 final int callingUid = Binder.getCallingUid();
2885 long ident = Binder.clearCallingIdentity();
2886 try {
2887 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002888 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002889
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002890 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 } finally {
2892 Binder.restoreCallingIdentity(ident);
2893 }
2894 }
2895
Louis Changcdec0802019-11-11 11:45:07 +08002896 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 final int callingUid = Binder.getCallingUid();
2898 long ident = Binder.clearCallingIdentity();
2899 try {
2900 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002901 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2904 // task and jumping straight into a call in the case of emergency call back.
2905 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2906 if (tm != null) {
2907 tm.showInCallScreen(false);
2908 }
2909 } finally {
2910 Binder.restoreCallingIdentity(ident);
2911 }
2912 }
2913
2914 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002915 public void updateLockTaskPackages(int userId, String[] packages) {
2916 final int callingUid = Binder.getCallingUid();
2917 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2918 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2919 "updateLockTaskPackages()");
2920 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002921 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002922 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2923 + Arrays.toString(packages));
2924 getLockTaskController().updateLockTaskPackages(userId, packages);
2925 }
2926 }
2927
2928 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 public boolean isInLockTaskMode() {
2930 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2931 }
2932
2933 @Override
2934 public int getLockTaskModeState() {
2935 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002936 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 }
2938 }
2939
2940 @Override
2941 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2942 synchronized (mGlobalLock) {
2943 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2944 if (r != null) {
2945 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002946 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 }
2949 }
2950 }
2951
2952 @Override
2953 public Bundle getActivityOptions(IBinder token) {
2954 final long origId = Binder.clearCallingIdentity();
2955 try {
2956 synchronized (mGlobalLock) {
2957 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2958 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002959 final ActivityOptions activityOptions = r.takeOptionsLocked(
2960 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 return activityOptions == null ? null : activityOptions.toBundle();
2962 }
2963 return null;
2964 }
2965 } finally {
2966 Binder.restoreCallingIdentity(origId);
2967 }
2968 }
2969
2970 @Override
2971 public List<IBinder> getAppTasks(String callingPackage) {
2972 int callingUid = Binder.getCallingUid();
2973 long ident = Binder.clearCallingIdentity();
2974 try {
2975 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002976 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 }
2978 } finally {
2979 Binder.restoreCallingIdentity(ident);
2980 }
2981 }
2982
2983 @Override
2984 public void finishVoiceTask(IVoiceInteractionSession session) {
2985 synchronized (mGlobalLock) {
2986 final long origId = Binder.clearCallingIdentity();
2987 try {
2988 // TODO: VI Consider treating local voice interactions and voice tasks
2989 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002990 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002991 } finally {
2992 Binder.restoreCallingIdentity(origId);
2993 }
2994 }
2995
2996 }
2997
2998 @Override
2999 public boolean isTopOfTask(IBinder token) {
3000 synchronized (mGlobalLock) {
3001 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003002 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 }
3004 }
3005
3006 @Override
3007 public void notifyLaunchTaskBehindComplete(IBinder token) {
3008 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3009 }
3010
3011 @Override
3012 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003013 mH.post(() -> {
3014 synchronized (mGlobalLock) {
3015 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003016 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003017 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003018 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003019 } catch (RemoteException e) {
3020 }
3021 }
3022 }
3023
3024 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026
3027 /** Called from an app when assist data is ready. */
3028 @Override
3029 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3030 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003031 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 synchronized (pae) {
3033 pae.result = extras;
3034 pae.structure = structure;
3035 pae.content = content;
3036 if (referrer != null) {
3037 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3038 }
3039 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003040 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003041 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003042 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 structure.setHomeActivity(pae.isHome);
3044 }
3045 pae.haveResult = true;
3046 pae.notifyAll();
3047 if (pae.intent == null && pae.receiver == null) {
3048 // Caller is just waiting for the result.
3049 return;
3050 }
3051 }
3052 // We are now ready to launch the assist activity.
3053 IAssistDataReceiver sendReceiver = null;
3054 Bundle sendBundle = null;
3055 synchronized (mGlobalLock) {
3056 buildAssistBundleLocked(pae, extras);
3057 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003058 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 if (!exists) {
3060 // Timed out.
3061 return;
3062 }
3063
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003064 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003065 // Caller wants result sent back to them.
3066 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003067 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003068 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003069 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3070 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3072 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3073 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3074 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3075 }
3076 }
3077 if (sendReceiver != null) {
3078 try {
3079 sendReceiver.onHandleAssistData(sendBundle);
3080 } catch (RemoteException e) {
3081 }
3082 return;
3083 }
3084
3085 final long ident = Binder.clearCallingIdentity();
3086 try {
3087 if (TextUtils.equals(pae.intent.getAction(),
3088 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003089 // Start voice interaction through VoiceInteractionManagerService.
3090 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3091 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003092 } else {
3093 pae.intent.replaceExtras(pae.extras);
3094 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3095 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3096 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003097 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098
3099 try {
3100 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3101 } catch (ActivityNotFoundException e) {
3102 Slog.w(TAG, "No activity to handle assist action.", e);
3103 }
3104 }
3105 } finally {
3106 Binder.restoreCallingIdentity(ident);
3107 }
3108 }
3109
3110 @Override
3111 public int addAppTask(IBinder activityToken, Intent intent,
3112 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3113 final int callingUid = Binder.getCallingUid();
3114 final long callingIdent = Binder.clearCallingIdentity();
3115
3116 try {
3117 synchronized (mGlobalLock) {
3118 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3119 if (r == null) {
3120 throw new IllegalArgumentException("Activity does not exist; token="
3121 + activityToken);
3122 }
3123 ComponentName comp = intent.getComponent();
3124 if (comp == null) {
3125 throw new IllegalArgumentException("Intent " + intent
3126 + " must specify explicit component");
3127 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003128 if (thumbnail.getWidth() != mThumbnailWidth
3129 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003130 throw new IllegalArgumentException("Bad thumbnail size: got "
3131 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003132 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 }
3134 if (intent.getSelector() != null) {
3135 intent.setSelector(null);
3136 }
3137 if (intent.getSourceBounds() != null) {
3138 intent.setSourceBounds(null);
3139 }
3140 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3141 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3142 // The caller has added this as an auto-remove task... that makes no
3143 // sense, so turn off auto-remove.
3144 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3145 }
3146 }
3147 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3148 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3149 if (ainfo.applicationInfo.uid != callingUid) {
3150 throw new SecurityException(
3151 "Can't add task for another application: target uid="
3152 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3153 }
3154
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003155 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003156 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003157 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003159 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003161 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 return INVALID_TASK_ID;
3163 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003164 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165
3166 // TODO: Send the thumbnail to WM to store it.
3167
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003168 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 }
3170 } finally {
3171 Binder.restoreCallingIdentity(callingIdent);
3172 }
3173 }
3174
3175 @Override
3176 public Point getAppTaskThumbnailSize() {
3177 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003178 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 }
3180 }
3181
3182 @Override
3183 public void setTaskResizeable(int taskId, int resizeableMode) {
3184 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003185 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3187 if (task == null) {
3188 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3189 return;
3190 }
3191 task.setResizeMode(resizeableMode);
3192 }
3193 }
3194
3195 @Override
3196 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003197 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 long ident = Binder.clearCallingIdentity();
3199 try {
3200 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003201 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003202 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 if (task == null) {
3204 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3205 return;
3206 }
3207 // Place the task in the right stack if it isn't there already based on
3208 // the requested bounds.
3209 // The stack transition logic is:
3210 // - a null bounds on a freeform task moves that task to fullscreen
3211 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3212 // that task to freeform
3213 // - otherwise the task is not moved
3214 ActivityStack stack = task.getStack();
3215 if (!task.getWindowConfiguration().canResizeTask()) {
3216 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3217 }
3218 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3219 stack = stack.getDisplay().getOrCreateStack(
3220 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3221 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3222 stack = stack.getDisplay().getOrCreateStack(
3223 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3224 }
3225
3226 // Reparent the task to the right stack if necessary
3227 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3228 if (stack != task.getStack()) {
3229 // Defer resume until the task is resized below
3230 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3231 DEFER_RESUME, "resizeTask");
3232 preserveWindow = false;
3233 }
3234
3235 // After reparenting (which only resizes the task to the stack bounds), resize the
3236 // task to the actual bounds provided
3237 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3238 }
3239 } finally {
3240 Binder.restoreCallingIdentity(ident);
3241 }
3242 }
3243
Evan Roskyddedfd42019-10-04 13:38:38 -07003244 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3245 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003246 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003247 throw new RuntimeException("Invalid token in task transaction");
3248 }
3249 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3250 // masks here.
3251 int configMask = change.getConfigSetMask();
3252 int windowMask = change.getWindowSetMask();
3253 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3254 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3255 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3256 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3257 c.setTo(change.getConfiguration(), configMask, windowMask);
3258 container.onRequestedOverrideConfigurationChanged(c);
3259 }
3260
3261 @Override
3262 public void applyContainerTransaction(WindowContainerTransaction t) {
3263 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3264 long ident = Binder.clearCallingIdentity();
3265 try {
3266 if (t == null) {
3267 return;
3268 }
3269 synchronized (mGlobalLock) {
3270 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3271 t.getChanges().entrySet().iterator();
3272 while (entries.hasNext()) {
3273 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3274 entries.next();
3275 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3276 entry.getKey()).getContainer();
3277 sanitizeAndApplyConfigChange(cc, entry.getValue());
3278 }
3279 }
3280 } finally {
3281 Binder.restoreCallingIdentity(ident);
3282 }
3283 }
3284
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 @Override
3286 public boolean releaseActivityInstance(IBinder token) {
3287 synchronized (mGlobalLock) {
3288 final long origId = Binder.clearCallingIdentity();
3289 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003290 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3291 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003292 return false;
3293 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003294 r.destroyImmediately(true /* removeFromApp */, "app-req");
3295 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 } finally {
3297 Binder.restoreCallingIdentity(origId);
3298 }
3299 }
3300 }
3301
3302 @Override
3303 public void releaseSomeActivities(IApplicationThread appInt) {
3304 synchronized (mGlobalLock) {
3305 final long origId = Binder.clearCallingIdentity();
3306 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003307 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003308 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 } finally {
3310 Binder.restoreCallingIdentity(origId);
3311 }
3312 }
3313 }
3314
3315 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003316 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003317 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 != PackageManager.PERMISSION_GRANTED) {
3319 throw new SecurityException("Requires permission "
3320 + android.Manifest.permission.DEVICE_POWER);
3321 }
3322
3323 synchronized (mGlobalLock) {
3324 long ident = Binder.clearCallingIdentity();
3325 if (mKeyguardShown != keyguardShowing) {
3326 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003327 final Message msg = PooledLambda.obtainMessage(
3328 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3329 keyguardShowing);
3330 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 }
3332 try {
wilsonshih177261f2019-02-22 12:02:18 +08003333 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 } finally {
3335 Binder.restoreCallingIdentity(ident);
3336 }
3337 }
3338
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003339 mH.post(() -> {
3340 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3341 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3342 }
3343 });
3344 }
3345
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003346 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003347 mH.post(() -> {
3348 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3349 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3350 }
3351 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 }
3353
3354 @Override
3355 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003356 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3357 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358
3359 final File passedIconFile = new File(filePath);
3360 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3361 passedIconFile.getName());
3362 if (!legitIconFile.getPath().equals(filePath)
3363 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3364 throw new IllegalArgumentException("Bad file path: " + filePath
3365 + " passed for userId " + userId);
3366 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003367 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 }
3369
3370 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003372 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373 synchronized (mGlobalLock) {
3374 final long ident = Binder.clearCallingIdentity();
3375 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003376 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 if (stack == null) {
3378 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3379 return;
3380 }
3381 if (!stack.isActivityTypeStandardOrUndefined()) {
3382 throw new IllegalArgumentException(
3383 "Removing non-standard stack is not allowed.");
3384 }
3385 mStackSupervisor.removeStack(stack);
3386 } finally {
3387 Binder.restoreCallingIdentity(ident);
3388 }
3389 }
3390 }
3391
3392 @Override
3393 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003394 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395
3396 synchronized (mGlobalLock) {
3397 final long ident = Binder.clearCallingIdentity();
3398 try {
3399 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3400 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003401 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003402 } finally {
3403 Binder.restoreCallingIdentity(ident);
3404 }
3405 }
3406 }
3407
3408 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003409 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 synchronized (mGlobalLock) {
3411 long ident = Binder.clearCallingIdentity();
3412 try {
3413 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3414 if (r == null) {
3415 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003416 "toggleFreeformWindowingMode: No activity record matching token="
3417 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 }
3419
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003420 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003421 if (stack == null) {
3422 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3423 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 }
3425
Yunfan Chend967af82019-01-17 18:30:18 +09003426 if (!stack.inFreeformWindowingMode()
3427 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3428 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3429 + "toggle between fullscreen and freeform.");
3430 }
3431
3432 if (stack.inFreeformWindowingMode()) {
3433 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003434 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003435 throw new IllegalStateException("Size-compat windows are currently not"
3436 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003437 } else if (stack.getParent().inFreeformWindowingMode()) {
3438 // If the window is on a freeform display, set it to undefined. It will be
3439 // resolved to freeform and it can adjust windowing mode when the display mode
3440 // changes in runtime.
3441 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003442 } else {
3443 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3444 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 } finally {
3446 Binder.restoreCallingIdentity(ident);
3447 }
3448 }
3449 }
3450
3451 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3452 @Override
3453 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003454 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003456 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003457 }
3458
3459 /** Unregister a task stack listener so that it stops receiving callbacks. */
3460 @Override
3461 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003462 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003463 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003464 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 }
3466
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 @Override
3468 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3469 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3470 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3471 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3472 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3473 }
3474
3475 @Override
3476 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3477 IBinder activityToken, int flags) {
3478 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3479 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3480 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3481 }
3482
3483 @Override
3484 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3485 Bundle args) {
3486 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3487 true /* focused */, true /* newSessionId */, userHandle, args,
3488 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3489 }
3490
3491 @Override
3492 public Bundle getAssistContextExtras(int requestType) {
3493 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3494 null, null, true /* focused */, true /* newSessionId */,
3495 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3496 if (pae == null) {
3497 return null;
3498 }
3499 synchronized (pae) {
3500 while (!pae.haveResult) {
3501 try {
3502 pae.wait();
3503 } catch (InterruptedException e) {
3504 }
3505 }
3506 }
3507 synchronized (mGlobalLock) {
3508 buildAssistBundleLocked(pae, pae.result);
3509 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003510 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 }
3512 return pae.extras;
3513 }
3514
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003515 /**
3516 * Binder IPC calls go through the public entry point.
3517 * This can be called with or without the global lock held.
3518 */
3519 private static int checkCallingPermission(String permission) {
3520 return checkPermission(
3521 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3522 }
3523
3524 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003525 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003526 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3527 mAmInternal.enforceCallingPermission(permission, func);
3528 }
3529 }
3530
3531 @VisibleForTesting
3532 int checkGetTasksPermission(String permission, int pid, int uid) {
3533 return checkPermission(permission, pid, uid);
3534 }
3535
3536 static int checkPermission(String permission, int pid, int uid) {
3537 if (permission == null) {
3538 return PackageManager.PERMISSION_DENIED;
3539 }
3540 return checkComponentPermission(permission, pid, uid, -1, true);
3541 }
3542
Wale Ogunwale214f3482018-10-04 11:00:47 -07003543 public static int checkComponentPermission(String permission, int pid, int uid,
3544 int owningUid, boolean exported) {
3545 return ActivityManagerService.checkComponentPermission(
3546 permission, pid, uid, owningUid, exported);
3547 }
3548
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003549 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3550 if (getRecentTasks().isCallerRecents(callingUid)) {
3551 // Always allow the recents component to get tasks
3552 return true;
3553 }
3554
3555 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3556 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3557 if (!allowed) {
3558 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3559 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3560 // Temporary compatibility: some existing apps on the system image may
3561 // still be requesting the old permission and not switched to the new
3562 // one; if so, we'll still allow them full access. This means we need
3563 // to see if they are holding the old permission and are a system app.
3564 try {
3565 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3566 allowed = true;
3567 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3568 + " is using old GET_TASKS but privileged; allowing");
3569 }
3570 } catch (RemoteException e) {
3571 }
3572 }
3573 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3574 + " does not hold REAL_GET_TASKS; limiting output");
3575 }
3576 return allowed;
3577 }
3578
Nicholas Sauer0259e532019-08-30 08:24:55 -07003579 boolean isCrossUserAllowed(int pid, int uid) {
3580 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3581 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3582 }
3583
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003584 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3585 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3586 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3587 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003588 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589 "enqueueAssistContext()");
3590
3591 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003592 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003593 if (activity == null) {
3594 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3595 return null;
3596 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003597 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3599 return null;
3600 }
3601 if (focused) {
3602 if (activityToken != null) {
3603 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3604 if (activity != caller) {
3605 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3606 + " is not current top " + activity);
3607 return null;
3608 }
3609 }
3610 } else {
3611 activity = ActivityRecord.forTokenLocked(activityToken);
3612 if (activity == null) {
3613 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3614 + " couldn't be found");
3615 return null;
3616 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003617 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003618 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3619 return null;
3620 }
3621 }
3622
3623 PendingAssistExtras pae;
3624 Bundle extras = new Bundle();
3625 if (args != null) {
3626 extras.putAll(args);
3627 }
3628 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003629 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003630
3631 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3632 userHandle);
3633 pae.isHome = activity.isActivityTypeHome();
3634
3635 // Increment the sessionId if necessary
3636 if (newSessionId) {
3637 mViSessionId++;
3638 }
3639 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003640 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3641 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003643 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644 } catch (RemoteException e) {
3645 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3646 return null;
3647 }
3648 return pae;
3649 }
3650 }
3651
3652 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3653 if (result != null) {
3654 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3655 }
3656 if (pae.hint != null) {
3657 pae.extras.putBoolean(pae.hint, true);
3658 }
3659 }
3660
3661 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3662 IAssistDataReceiver receiver;
3663 synchronized (mGlobalLock) {
3664 mPendingAssistExtras.remove(pae);
3665 receiver = pae.receiver;
3666 }
3667 if (receiver != null) {
3668 // Caller wants result sent back to them.
3669 Bundle sendBundle = new Bundle();
3670 // At least return the receiver extras
3671 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3672 try {
3673 pae.receiver.onHandleAssistData(sendBundle);
3674 } catch (RemoteException e) {
3675 }
3676 }
3677 }
3678
3679 public class PendingAssistExtras extends Binder implements Runnable {
3680 public final ActivityRecord activity;
3681 public boolean isHome;
3682 public final Bundle extras;
3683 public final Intent intent;
3684 public final String hint;
3685 public final IAssistDataReceiver receiver;
3686 public final int userHandle;
3687 public boolean haveResult = false;
3688 public Bundle result = null;
3689 public AssistStructure structure = null;
3690 public AssistContent content = null;
3691 public Bundle receiverExtras;
3692
3693 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3694 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3695 int _userHandle) {
3696 activity = _activity;
3697 extras = _extras;
3698 intent = _intent;
3699 hint = _hint;
3700 receiver = _receiver;
3701 receiverExtras = _receiverExtras;
3702 userHandle = _userHandle;
3703 }
3704
3705 @Override
3706 public void run() {
3707 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3708 synchronized (this) {
3709 haveResult = true;
3710 notifyAll();
3711 }
3712 pendingAssistExtrasTimedOut(this);
3713 }
3714 }
3715
3716 @Override
3717 public boolean isAssistDataAllowedOnCurrentActivity() {
3718 int userId;
3719 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003720 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003721 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3722 return false;
3723 }
3724
Wale Ogunwale21e06482019-11-18 05:14:15 -08003725 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003726 if (activity == null) {
3727 return false;
3728 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003729 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003730 }
3731 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3732 }
3733
3734 @Override
3735 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3736 long ident = Binder.clearCallingIdentity();
3737 try {
3738 synchronized (mGlobalLock) {
3739 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003740 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003741 if (top != caller) {
3742 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3743 + " is not current top " + top);
3744 return false;
3745 }
3746 if (!top.nowVisible) {
3747 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3748 + " is not visible");
3749 return false;
3750 }
3751 }
3752 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3753 token);
3754 } finally {
3755 Binder.restoreCallingIdentity(ident);
3756 }
3757 }
3758
3759 @Override
3760 public boolean isRootVoiceInteraction(IBinder token) {
3761 synchronized (mGlobalLock) {
3762 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3763 if (r == null) {
3764 return false;
3765 }
3766 return r.rootVoiceInteraction;
3767 }
3768 }
3769
Wale Ogunwalef6733932018-06-27 05:14:34 -07003770 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3771 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3772 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3773 if (activityToCallback == null) return;
3774 activityToCallback.setVoiceSessionLocked(voiceSession);
3775
3776 // Inform the activity
3777 try {
3778 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3779 voiceInteractor);
3780 long token = Binder.clearCallingIdentity();
3781 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003782 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003783 } finally {
3784 Binder.restoreCallingIdentity(token);
3785 }
3786 // TODO: VI Should we cache the activity so that it's easier to find later
3787 // rather than scan through all the stacks and activities?
3788 } catch (RemoteException re) {
3789 activityToCallback.clearVoiceSessionLocked();
3790 // TODO: VI Should this terminate the voice session?
3791 }
3792 }
3793
3794 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3795 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3796 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3797 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3798 boolean wasRunningVoice = mRunningVoice != null;
3799 mRunningVoice = session;
3800 if (!wasRunningVoice) {
3801 mVoiceWakeLock.acquire();
3802 updateSleepIfNeededLocked();
3803 }
3804 }
3805 }
3806
3807 void finishRunningVoiceLocked() {
3808 if (mRunningVoice != null) {
3809 mRunningVoice = null;
3810 mVoiceWakeLock.release();
3811 updateSleepIfNeededLocked();
3812 }
3813 }
3814
3815 @Override
3816 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3817 synchronized (mGlobalLock) {
3818 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3819 if (keepAwake) {
3820 mVoiceWakeLock.acquire();
3821 } else {
3822 mVoiceWakeLock.release();
3823 }
3824 }
3825 }
3826 }
3827
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 @Override
3829 public ComponentName getActivityClassForToken(IBinder token) {
3830 synchronized (mGlobalLock) {
3831 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3832 if (r == null) {
3833 return null;
3834 }
3835 return r.intent.getComponent();
3836 }
3837 }
3838
3839 @Override
3840 public String getPackageForToken(IBinder token) {
3841 synchronized (mGlobalLock) {
3842 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3843 if (r == null) {
3844 return null;
3845 }
3846 return r.packageName;
3847 }
3848 }
3849
3850 @Override
3851 public void showLockTaskEscapeMessage(IBinder token) {
3852 synchronized (mGlobalLock) {
3853 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3854 if (r == null) {
3855 return;
3856 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003857 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003858 }
3859 }
3860
3861 @Override
3862 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003863 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 final long token = Binder.clearCallingIdentity();
3865 try {
3866 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003867 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003868 }
3869 } finally {
3870 Binder.restoreCallingIdentity(token);
3871 }
3872 }
3873
3874 /**
3875 * Try to place task to provided position. The final position might be different depending on
3876 * current user and stacks state. The task will be moved to target stack if it's currently in
3877 * different stack.
3878 */
3879 @Override
3880 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003881 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 synchronized (mGlobalLock) {
3883 long ident = Binder.clearCallingIdentity();
3884 try {
3885 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3886 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003887 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 if (task == null) {
3889 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3890 + taskId);
3891 }
3892
Wale Ogunwaled32da472018-11-16 07:19:28 -08003893 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894
3895 if (stack == null) {
3896 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3897 + stackId);
3898 }
3899 if (!stack.isActivityTypeStandardOrUndefined()) {
3900 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3901 + " the position of task " + taskId + " in/to non-standard stack");
3902 }
3903
3904 // TODO: Have the callers of this API call a separate reparent method if that is
3905 // what they intended to do vs. having this method also do reparenting.
3906 if (task.getStack() == stack) {
3907 // Change position in current stack.
3908 stack.positionChildAt(task, position);
3909 } else {
3910 // Reparent to new stack.
3911 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3912 !DEFER_RESUME, "positionTaskInStack");
3913 }
3914 } finally {
3915 Binder.restoreCallingIdentity(ident);
3916 }
3917 }
3918 }
3919
3920 @Override
3921 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3922 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3923 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003924 + Arrays.toString(horizontalSizeConfiguration) + " "
3925 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003926 synchronized (mGlobalLock) {
3927 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3928 if (record == null) {
3929 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3930 + "found for: " + token);
3931 }
3932 record.setSizeConfigurations(horizontalSizeConfiguration,
3933 verticalSizeConfigurations, smallestSizeConfigurations);
3934 }
3935 }
3936
3937 /**
3938 * Dismisses split-screen multi-window mode.
3939 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3940 */
3941 @Override
3942 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003943 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003944 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3945 final long ident = Binder.clearCallingIdentity();
3946 try {
3947 synchronized (mGlobalLock) {
3948 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003949 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 if (stack == null) {
3951 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3952 return;
3953 }
3954
3955 if (toTop) {
3956 // Caller wants the current split-screen primary stack to be the top stack after
3957 // it goes fullscreen, so move it to the front.
3958 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003959 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003961 // stack after it goes fullscreen, so we move the focus to the top-most
3962 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3964 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3965 if (otherStack != null) {
3966 otherStack.moveToFront("dismissSplitScreenMode_other");
3967 }
3968 }
3969
Evan Rosky10475742018-09-05 19:02:48 -07003970 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 }
3972 } finally {
3973 Binder.restoreCallingIdentity(ident);
3974 }
3975 }
3976
3977 /**
3978 * Dismisses Pip
3979 * @param animate True if the dismissal should be animated.
3980 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3981 * default animation duration should be used.
3982 */
3983 @Override
3984 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003985 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003986 final long ident = Binder.clearCallingIdentity();
3987 try {
3988 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003989 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003990 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 if (stack == null) {
3992 Slog.w(TAG, "dismissPip: pinned stack not found.");
3993 return;
3994 }
3995 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3996 throw new IllegalArgumentException("Stack: " + stack
3997 + " doesn't support animated resize.");
3998 }
3999 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004000 stack.animateResizePinnedStack(null /* destBounds */,
4001 null /* sourceHintBounds */, animationDuration,
4002 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004004 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 }
4006 }
4007 } finally {
4008 Binder.restoreCallingIdentity(ident);
4009 }
4010 }
4011
4012 @Override
4013 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004014 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 synchronized (mGlobalLock) {
4016 mSuppressResizeConfigChanges = suppress;
4017 }
4018 }
4019
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 @Override
4021 // TODO: API should just be about changing windowing modes...
4022 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004023 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 "moveTasksToFullscreenStack()");
4025 synchronized (mGlobalLock) {
4026 final long origId = Binder.clearCallingIdentity();
4027 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004028 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 if (stack != null){
4030 if (!stack.isActivityTypeStandardOrUndefined()) {
4031 throw new IllegalArgumentException(
4032 "You can't move tasks from non-standard stacks.");
4033 }
4034 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4035 }
4036 } finally {
4037 Binder.restoreCallingIdentity(origId);
4038 }
4039 }
4040 }
4041
4042 /**
4043 * Moves the top activity in the input stackId to the pinned stack.
4044 *
4045 * @param stackId Id of stack to move the top activity to pinned stack.
4046 * @param bounds Bounds to use for pinned stack.
4047 *
4048 * @return True if the top activity of the input stack was successfully moved to the pinned
4049 * stack.
4050 */
4051 @Override
4052 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004053 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004054 "moveTopActivityToPinnedStack()");
4055 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004056 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4058 + "Device doesn't support picture-in-picture mode");
4059 }
4060
4061 long ident = Binder.clearCallingIdentity();
4062 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004063 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064 } finally {
4065 Binder.restoreCallingIdentity(ident);
4066 }
4067 }
4068 }
4069
4070 @Override
4071 public boolean isInMultiWindowMode(IBinder token) {
4072 final long origId = Binder.clearCallingIdentity();
4073 try {
4074 synchronized (mGlobalLock) {
4075 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4076 if (r == null) {
4077 return false;
4078 }
4079 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4080 return r.inMultiWindowMode();
4081 }
4082 } finally {
4083 Binder.restoreCallingIdentity(origId);
4084 }
4085 }
4086
4087 @Override
4088 public boolean isInPictureInPictureMode(IBinder token) {
4089 final long origId = Binder.clearCallingIdentity();
4090 try {
4091 synchronized (mGlobalLock) {
4092 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4093 }
4094 } finally {
4095 Binder.restoreCallingIdentity(origId);
4096 }
4097 }
4098
4099 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004100 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4101 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004102 return false;
4103 }
4104
4105 // If we are animating to fullscreen then we have already dispatched the PIP mode
4106 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004107 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004108 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004109 }
4110
4111 @Override
4112 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4113 final long origId = Binder.clearCallingIdentity();
4114 try {
4115 synchronized (mGlobalLock) {
4116 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4117 "enterPictureInPictureMode", token, params);
4118
4119 // If the activity is already in picture in picture mode, then just return early
4120 if (isInPictureInPictureMode(r)) {
4121 return true;
4122 }
4123
4124 // Activity supports picture-in-picture, now check that we can enter PiP at this
4125 // point, if it is
4126 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4127 false /* beforeStopping */)) {
4128 return false;
4129 }
4130
4131 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004132 synchronized (mGlobalLock) {
4133 // Only update the saved args from the args that are set
4134 r.pictureInPictureArgs.copyOnlySet(params);
4135 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4136 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4137 // Adjust the source bounds by the insets for the transition down
4138 final Rect sourceBounds = new Rect(
4139 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004140 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004141 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004142 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004143 stack.setPictureInPictureAspectRatio(aspectRatio);
4144 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004145 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4146 r.info.applicationInfo.uid, r.shortComponentName,
4147 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004148 logPictureInPictureArgs(params);
4149 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 };
4151
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004152 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004153 // If the keyguard is showing or occluded, then try and dismiss it before
4154 // entering picture-in-picture (this will prompt the user to authenticate if the
4155 // device is currently locked).
4156 dismissKeyguard(token, new KeyguardDismissCallback() {
4157 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 public void onDismissSucceeded() {
4159 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 }
4161 }, null /* message */);
4162 } else {
4163 // Enter picture in picture immediately otherwise
4164 enterPipRunnable.run();
4165 }
4166 return true;
4167 }
4168 } finally {
4169 Binder.restoreCallingIdentity(origId);
4170 }
4171 }
4172
4173 @Override
4174 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4175 final long origId = Binder.clearCallingIdentity();
4176 try {
4177 synchronized (mGlobalLock) {
4178 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4179 "setPictureInPictureParams", token, params);
4180
4181 // Only update the saved args from the args that are set
4182 r.pictureInPictureArgs.copyOnlySet(params);
4183 if (r.inPinnedWindowingMode()) {
4184 // If the activity is already in picture-in-picture, update the pinned stack now
4185 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4186 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004187 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 if (!stack.isAnimatingBoundsToFullscreen()) {
4189 stack.setPictureInPictureAspectRatio(
4190 r.pictureInPictureArgs.getAspectRatio());
4191 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4192 }
4193 }
4194 logPictureInPictureArgs(params);
4195 }
4196 } finally {
4197 Binder.restoreCallingIdentity(origId);
4198 }
4199 }
4200
4201 @Override
4202 public int getMaxNumPictureInPictureActions(IBinder token) {
4203 // Currently, this is a static constant, but later, we may change this to be dependent on
4204 // the context of the activity
4205 return 3;
4206 }
4207
4208 private void logPictureInPictureArgs(PictureInPictureParams params) {
4209 if (params.hasSetActions()) {
4210 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4211 params.getActions().size());
4212 }
4213 if (params.hasSetAspectRatio()) {
4214 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4215 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4216 MetricsLogger.action(lm);
4217 }
4218 }
4219
4220 /**
4221 * Checks the state of the system and the activity associated with the given {@param token} to
4222 * verify that picture-in-picture is supported for that activity.
4223 *
4224 * @return the activity record for the given {@param token} if all the checks pass.
4225 */
4226 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4227 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004228 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 throw new IllegalStateException(caller
4230 + ": Device doesn't support picture-in-picture mode.");
4231 }
4232
4233 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4234 if (r == null) {
4235 throw new IllegalStateException(caller
4236 + ": Can't find activity for token=" + token);
4237 }
4238
4239 if (!r.supportsPictureInPicture()) {
4240 throw new IllegalStateException(caller
4241 + ": Current activity does not support picture-in-picture.");
4242 }
4243
4244 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004245 && !mWindowManager.isValidPictureInPictureAspectRatio(
4246 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 final float minAspectRatio = mContext.getResources().getFloat(
4248 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4249 final float maxAspectRatio = mContext.getResources().getFloat(
4250 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4251 throw new IllegalArgumentException(String.format(caller
4252 + ": Aspect ratio is too extreme (must be between %f and %f).",
4253 minAspectRatio, maxAspectRatio));
4254 }
4255
4256 // Truncate the number of actions if necessary
4257 params.truncateActions(getMaxNumPictureInPictureActions(token));
4258
4259 return r;
4260 }
4261
4262 @Override
4263 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004264 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004265 synchronized (mGlobalLock) {
4266 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4267 if (r == null) {
4268 throw new IllegalArgumentException("Activity does not exist; token="
4269 + activityToken);
4270 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004271 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272 }
4273 }
4274
4275 @Override
4276 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4277 Rect tempDockedTaskInsetBounds,
4278 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004279 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 long ident = Binder.clearCallingIdentity();
4281 try {
4282 synchronized (mGlobalLock) {
4283 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4284 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4285 PRESERVE_WINDOWS);
4286 }
4287 } finally {
4288 Binder.restoreCallingIdentity(ident);
4289 }
4290 }
4291
4292 @Override
4293 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004294 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004295 final long ident = Binder.clearCallingIdentity();
4296 try {
4297 synchronized (mGlobalLock) {
4298 mStackSupervisor.setSplitScreenResizing(resizing);
4299 }
4300 } finally {
4301 Binder.restoreCallingIdentity(ident);
4302 }
4303 }
4304
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004305 /**
4306 * Check that we have the features required for VR-related API calls, and throw an exception if
4307 * not.
4308 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004309 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 if (!mContext.getPackageManager().hasSystemFeature(
4311 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4312 throw new UnsupportedOperationException("VR mode not supported on this device!");
4313 }
4314 }
4315
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 @Override
4317 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004318 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004319
4320 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4321
4322 ActivityRecord r;
4323 synchronized (mGlobalLock) {
4324 r = ActivityRecord.isInStackLocked(token);
4325 }
4326
4327 if (r == null) {
4328 throw new IllegalArgumentException();
4329 }
4330
4331 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004332 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 VrManagerInternal.NO_ERROR) {
4334 return err;
4335 }
4336
4337 // Clear the binder calling uid since this path may call moveToTask().
4338 final long callingId = Binder.clearCallingIdentity();
4339 try {
4340 synchronized (mGlobalLock) {
4341 r.requestedVrComponent = (enabled) ? packageName : null;
4342
4343 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004344 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004345 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 }
4347 return 0;
4348 }
4349 } finally {
4350 Binder.restoreCallingIdentity(callingId);
4351 }
4352 }
4353
4354 @Override
4355 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4356 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4357 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004358 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4360 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4361 }
Louis Changcdec0802019-11-11 11:45:07 +08004362 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 || activity.voiceSession != null) {
4364 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4365 return;
4366 }
4367 if (activity.pendingVoiceInteractionStart) {
4368 Slog.w(TAG, "Pending start of voice interaction already.");
4369 return;
4370 }
4371 activity.pendingVoiceInteractionStart = true;
4372 }
4373 LocalServices.getService(VoiceInteractionManagerInternal.class)
4374 .startLocalVoiceInteraction(callingActivity, options);
4375 }
4376
4377 @Override
4378 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4379 LocalServices.getService(VoiceInteractionManagerInternal.class)
4380 .stopLocalVoiceInteraction(callingActivity);
4381 }
4382
4383 @Override
4384 public boolean supportsLocalVoiceInteraction() {
4385 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4386 .supportsLocalVoiceInteraction();
4387 }
4388
4389 /** Notifies all listeners when the pinned stack animation starts. */
4390 @Override
4391 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004392 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 }
4394
4395 /** Notifies all listeners when the pinned stack animation ends. */
4396 @Override
4397 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004398 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 }
4400
4401 @Override
4402 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004403 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 final long ident = Binder.clearCallingIdentity();
4405 try {
4406 synchronized (mGlobalLock) {
4407 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4408 }
4409 } finally {
4410 Binder.restoreCallingIdentity(ident);
4411 }
4412 }
4413
4414 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004416 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004417
4418 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004419 if (mWindowManager == null) {
4420 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4421 return false;
4422 }
4423
4424 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004425 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 }
4428
Riddle Hsua0022cd2019-09-09 21:12:41 +08004429 mH.sendMessage(PooledLambda.obtainMessage(
4430 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4431 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432
4433 final long origId = Binder.clearCallingIdentity();
4434 try {
4435 if (values != null) {
4436 Settings.System.clearConfiguration(values);
4437 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004439 UserHandle.USER_NULL, false /* deferResume */,
4440 mTmpUpdateConfigurationResult);
4441 return mTmpUpdateConfigurationResult.changes != 0;
4442 } finally {
4443 Binder.restoreCallingIdentity(origId);
4444 }
4445 }
4446 }
4447
4448 @Override
4449 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4450 CharSequence message) {
4451 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4454 }
4455 final long callingId = Binder.clearCallingIdentity();
4456 try {
4457 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004458 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 }
4460 } finally {
4461 Binder.restoreCallingIdentity(callingId);
4462 }
4463 }
4464
4465 @Override
4466 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 "cancelTaskWindowTransition()");
4469 final long ident = Binder.clearCallingIdentity();
4470 try {
4471 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004472 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 MATCH_TASK_IN_STACKS_ONLY);
4474 if (task == null) {
4475 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4476 return;
4477 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004478 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479 }
4480 } finally {
4481 Binder.restoreCallingIdentity(ident);
4482 }
4483 }
4484
4485 @Override
4486 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004487 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 final long ident = Binder.clearCallingIdentity();
4489 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004490 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 } finally {
4492 Binder.restoreCallingIdentity(ident);
4493 }
4494 }
4495
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004496 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4497 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004498 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004499 synchronized (mGlobalLock) {
4500 task = mRootActivityContainer.anyTaskForId(taskId,
4501 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4502 if (task == null) {
4503 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4504 return null;
4505 }
4506 }
4507 // Don't call this while holding the lock as this operation might hit the disk.
4508 return task.getSnapshot(reducedResolution, restoreFromDisk);
4509 }
4510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 @Override
4512 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4513 synchronized (mGlobalLock) {
4514 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4515 if (r == null) {
4516 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4517 + token);
4518 return;
4519 }
4520 final long origId = Binder.clearCallingIdentity();
4521 try {
4522 r.setDisablePreviewScreenshots(disable);
4523 } finally {
4524 Binder.restoreCallingIdentity(origId);
4525 }
4526 }
4527 }
4528
4529 /** Return the user id of the last resumed activity. */
4530 @Override
4531 public @UserIdInt
4532 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004533 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004534 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4535 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004536 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004537 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004539 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 }
4541 }
4542
4543 @Override
4544 public void updateLockTaskFeatures(int userId, int flags) {
4545 final int callingUid = Binder.getCallingUid();
4546 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004547 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 "updateLockTaskFeatures()");
4549 }
4550 synchronized (mGlobalLock) {
4551 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4552 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004553 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 }
4555 }
4556
4557 @Override
4558 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4559 synchronized (mGlobalLock) {
4560 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4561 if (r == null) {
4562 return;
4563 }
4564 final long origId = Binder.clearCallingIdentity();
4565 try {
4566 r.setShowWhenLocked(showWhenLocked);
4567 } finally {
4568 Binder.restoreCallingIdentity(origId);
4569 }
4570 }
4571 }
4572
4573 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004574 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4575 synchronized (mGlobalLock) {
4576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4577 if (r == null) {
4578 return;
4579 }
4580 final long origId = Binder.clearCallingIdentity();
4581 try {
4582 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4583 } finally {
4584 Binder.restoreCallingIdentity(origId);
4585 }
4586 }
4587 }
4588
4589 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004590 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4591 synchronized (mGlobalLock) {
4592 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4593 if (r == null) {
4594 return;
4595 }
4596 final long origId = Binder.clearCallingIdentity();
4597 try {
4598 r.setTurnScreenOn(turnScreenOn);
4599 } finally {
4600 Binder.restoreCallingIdentity(origId);
4601 }
4602 }
4603 }
4604
4605 @Override
4606 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004607 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004608 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004609 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004610 synchronized (mGlobalLock) {
4611 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4612 if (r == null) {
4613 return;
4614 }
4615 final long origId = Binder.clearCallingIdentity();
4616 try {
4617 r.registerRemoteAnimations(definition);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
4624 @Override
4625 public void registerRemoteAnimationForNextActivityStart(String packageName,
4626 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004629 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 synchronized (mGlobalLock) {
4631 final long origId = Binder.clearCallingIdentity();
4632 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004633 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004634 packageName, adapter);
4635 } finally {
4636 Binder.restoreCallingIdentity(origId);
4637 }
4638 }
4639 }
4640
Evan Rosky966759f2019-01-15 10:33:58 -08004641 @Override
4642 public void registerRemoteAnimationsForDisplay(int displayId,
4643 RemoteAnimationDefinition definition) {
4644 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4645 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004646 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004647 synchronized (mGlobalLock) {
4648 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4649 if (display == null) {
4650 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4651 return;
4652 }
4653 final long origId = Binder.clearCallingIdentity();
4654 try {
4655 display.mDisplayContent.registerRemoteAnimations(definition);
4656 } finally {
4657 Binder.restoreCallingIdentity(origId);
4658 }
4659 }
4660 }
4661
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004662 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4663 @Override
4664 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4665 synchronized (mGlobalLock) {
4666 final long origId = Binder.clearCallingIdentity();
4667 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004668 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 } finally {
4670 Binder.restoreCallingIdentity(origId);
4671 }
4672 }
4673 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004674
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004675 @Override
4676 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004677 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004678 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004679 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004680 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004681 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004682 }
4683 }
4684
4685 @Override
4686 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004688 != PERMISSION_GRANTED) {
4689 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4690 + Binder.getCallingPid()
4691 + ", uid=" + Binder.getCallingUid()
4692 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4693 Slog.w(TAG, msg);
4694 throw new SecurityException(msg);
4695 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004696 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004697 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004698 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004699 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004700 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004701 }
4702 }
4703
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004704 @Override
4705 public void stopAppSwitches() {
4706 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4707 synchronized (mGlobalLock) {
4708 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004709 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004710 mDidAppSwitch = false;
4711 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4712 }
4713 }
4714
4715 @Override
4716 public void resumeAppSwitches() {
4717 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4718 synchronized (mGlobalLock) {
4719 // Note that we don't execute any pending app switches... we will
4720 // let those wait until either the timeout, or the next start
4721 // activity request.
4722 mAppSwitchesAllowedTime = 0;
4723 }
4724 }
4725
Ricky Wai906af482019-06-03 17:25:28 +01004726 long getLastStopAppSwitchesTime() {
4727 return mLastStopAppSwitchesTime;
4728 }
4729
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004730 void onStartActivitySetDidAppSwitch() {
4731 if (mDidAppSwitch) {
4732 // This is the second allowed switch since we stopped switches, so now just generally
4733 // allow switches. Use case:
4734 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4735 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4736 // anyone to switch again).
4737 mAppSwitchesAllowedTime = 0;
4738 } else {
4739 mDidAppSwitch = true;
4740 }
4741 }
4742
4743 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 boolean shouldDisableNonVrUiLocked() {
4745 return mVrController.shouldDisableNonVrUiLocked();
4746 }
4747
Wale Ogunwale53783742018-09-16 10:21:51 -07004748 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 // 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 +00004750 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004751 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004752 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4753 + " to main display for VR");
4754 mRootActivityContainer.moveStackToDisplay(
4755 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004756 }
4757 mH.post(() -> {
4758 if (!mVrController.onVrModeChanged(r)) {
4759 return;
4760 }
4761 synchronized (mGlobalLock) {
4762 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4763 mWindowManager.disableNonVrUi(disableNonVrUi);
4764 if (disableNonVrUi) {
4765 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4766 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004767 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004768 }
4769 }
4770 });
4771 }
4772
Wale Ogunwale53783742018-09-16 10:21:51 -07004773 @Override
4774 public int getPackageScreenCompatMode(String packageName) {
4775 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4776 synchronized (mGlobalLock) {
4777 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4778 }
4779 }
4780
4781 @Override
4782 public void setPackageScreenCompatMode(String packageName, int mode) {
4783 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4784 "setPackageScreenCompatMode");
4785 synchronized (mGlobalLock) {
4786 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4787 }
4788 }
4789
4790 @Override
4791 public boolean getPackageAskScreenCompat(String packageName) {
4792 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4793 synchronized (mGlobalLock) {
4794 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4795 }
4796 }
4797
4798 @Override
4799 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4800 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4801 "setPackageAskScreenCompat");
4802 synchronized (mGlobalLock) {
4803 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4804 }
4805 }
4806
Wale Ogunwale64258362018-10-16 15:13:37 -07004807 public static String relaunchReasonToString(int relaunchReason) {
4808 switch (relaunchReason) {
4809 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4810 return "window_resize";
4811 case RELAUNCH_REASON_FREE_RESIZE:
4812 return "free_resize";
4813 default:
4814 return null;
4815 }
4816 }
4817
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004818 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004819 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004820 }
4821
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004822 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004823 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004824 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4825 }
4826
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004827 boolean isKeyguardLocked() {
4828 return mKeyguardController.isKeyguardLocked();
4829 }
4830
Garfield Tan01548632018-11-27 10:15:48 -08004831 /**
4832 * Clears launch params for the given package.
4833 * @param packageNames the names of the packages of which the launch params are to be cleared
4834 */
4835 @Override
4836 public void clearLaunchParamsForPackages(List<String> packageNames) {
4837 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4838 "clearLaunchParamsForPackages");
4839 synchronized (mGlobalLock) {
4840 for (int i = 0; i < packageNames.size(); ++i) {
4841 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4842 }
4843 }
4844 }
4845
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004846 /**
4847 * Makes the display with the given id a single task instance display. I.e the display can only
4848 * contain one task.
4849 */
4850 @Override
4851 public void setDisplayToSingleTaskInstance(int displayId) {
4852 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4853 "setDisplayToSingleTaskInstance");
4854 final long origId = Binder.clearCallingIdentity();
4855 try {
4856 final ActivityDisplay display =
4857 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4858 if (display != null) {
4859 display.setDisplayToSingleTaskInstance();
4860 }
4861 } finally {
4862 Binder.restoreCallingIdentity(origId);
4863 }
4864 }
4865
Wale Ogunwale31913b52018-10-13 08:29:31 -07004866 void dumpLastANRLocked(PrintWriter pw) {
4867 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4868 if (mLastANRState == null) {
4869 pw.println(" <no ANR has occurred since boot>");
4870 } else {
4871 pw.println(mLastANRState);
4872 }
4873 }
4874
4875 void dumpLastANRTracesLocked(PrintWriter pw) {
4876 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4877
4878 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4879 if (ArrayUtils.isEmpty(files)) {
4880 pw.println(" <no ANR has occurred since boot>");
4881 return;
4882 }
4883 // Find the latest file.
4884 File latest = null;
4885 for (File f : files) {
4886 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4887 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004888 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004889 }
4890 pw.print("File: ");
4891 pw.print(latest.getName());
4892 pw.println();
4893 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4894 String line;
4895 while ((line = in.readLine()) != null) {
4896 pw.println(line);
4897 }
4898 } catch (IOException e) {
4899 pw.print("Unable to read: ");
4900 pw.print(e);
4901 pw.println();
4902 }
4903 }
4904
4905 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4906 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4907 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4908 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4909 }
4910
4911 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4912 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4913 pw.println(header);
4914
Wale Ogunwaled32da472018-11-16 07:19:28 -08004915 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004916 dumpPackage);
4917 boolean needSep = printedAnything;
4918
4919 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004920 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004921 " ResumedActivity: ");
4922 if (printed) {
4923 printedAnything = true;
4924 needSep = false;
4925 }
4926
4927 if (dumpPackage == null) {
4928 if (needSep) {
4929 pw.println();
4930 }
4931 printedAnything = true;
4932 mStackSupervisor.dump(pw, " ");
4933 }
4934
4935 if (!printedAnything) {
4936 pw.println(" (nothing)");
4937 }
4938 }
4939
4940 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004941 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004942 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004943 pw.println(" ");
4944 }
4945
4946 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4947 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4948 getActivityStartController().dump(pw, "", dumpPackage);
4949 }
4950
4951 /**
4952 * There are three things that cmd can be:
4953 * - a flattened component name that matches an existing activity
4954 * - the cmd arg isn't the flattened component name of an existing activity:
4955 * dump all activity whose component contains the cmd as a substring
4956 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004957 * <p>
4958 * The caller should not hold lock when calling this method because it will wait for the
4959 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004960 *
4961 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4962 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4963 */
4964 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4965 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4966 ArrayList<ActivityRecord> activities;
4967
4968 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004969 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004970 dumpFocusedStackOnly);
4971 }
4972
4973 if (activities.size() <= 0) {
4974 return false;
4975 }
4976
4977 String[] newArgs = new String[args.length - opti];
4978 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4979
Louis Changcdec0802019-11-11 11:45:07 +08004980 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004981 boolean needSep = false;
4982 for (int i = activities.size() - 1; i >= 0; i--) {
4983 ActivityRecord r = activities.get(i);
4984 if (needSep) {
4985 pw.println();
4986 }
4987 needSep = true;
4988 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004989 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 if (lastTask != task) {
4991 lastTask = task;
4992 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004993 pw.print(" id="); pw.print(lastTask.mTaskId);
4994 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 if (dumpAll) {
4996 lastTask.dump(pw, " ");
4997 }
4998 }
4999 }
5000 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5001 }
5002 return true;
5003 }
5004
5005 /**
5006 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5007 * there is a thread associated with the activity.
5008 */
5009 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5010 final ActivityRecord r, String[] args, boolean dumpAll) {
5011 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005012 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005013 synchronized (mGlobalLock) {
5014 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5015 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5016 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005017 if (r.hasProcess()) {
5018 pw.println(r.app.getPid());
5019 appThread = r.app.getThread();
5020 } else {
5021 pw.println("(not running)");
5022 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005023 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005024 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005025 }
5026 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005027 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005028 // flush anything that is already in the PrintWriter since the thread is going
5029 // to write to the file descriptor directly
5030 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005031 try (TransferPipe tp = new TransferPipe()) {
5032 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5033 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005034 } catch (IOException e) {
5035 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5036 } catch (RemoteException e) {
5037 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5038 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005039 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005040 }
5041
sanryhuang498e77e2018-12-06 14:57:01 +08005042 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5043 boolean testPssMode) {
5044 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5045 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5046 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005047 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005048 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5049 st.toString());
5050 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005051 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5052 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5053 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005054 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5055 testPssMode);
5056 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005057 }
5058
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005059 int getCurrentUserId() {
5060 return mAmInternal.getCurrentUserId();
5061 }
5062
5063 private void enforceNotIsolatedCaller(String caller) {
5064 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5065 throw new SecurityException("Isolated process not allowed to call " + caller);
5066 }
5067 }
5068
Wale Ogunwalef6733932018-06-27 05:14:34 -07005069 public Configuration getConfiguration() {
5070 Configuration ci;
5071 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005072 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005073 ci.userSetLocale = false;
5074 }
5075 return ci;
5076 }
5077
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005078 /**
5079 * Current global configuration information. Contains general settings for the entire system,
5080 * also corresponds to the merged configuration of the default display.
5081 */
5082 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005083 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005084 }
5085
5086 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5087 boolean initLocale) {
5088 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5089 }
5090
5091 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5092 boolean initLocale, boolean deferResume) {
5093 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5094 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5095 UserHandle.USER_NULL, deferResume);
5096 }
5097
Wale Ogunwale59507092018-10-29 09:00:30 -07005098 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005099 final long origId = Binder.clearCallingIdentity();
5100 try {
5101 synchronized (mGlobalLock) {
5102 updateConfigurationLocked(values, null, false, true, userId,
5103 false /* deferResume */);
5104 }
5105 } finally {
5106 Binder.restoreCallingIdentity(origId);
5107 }
5108 }
5109
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005110 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5111 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5112 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5113 deferResume, null /* result */);
5114 }
5115
5116 /**
5117 * Do either or both things: (1) change the current configuration, and (2)
5118 * make sure the given activity is running with the (now) current
5119 * configuration. Returns true if the activity has been left running, or
5120 * false if <var>starting</var> is being destroyed to match the new
5121 * configuration.
5122 *
5123 * @param userId is only used when persistent parameter is set to true to persist configuration
5124 * for that particular user
5125 */
5126 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5127 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5128 ActivityTaskManagerService.UpdateConfigurationResult result) {
5129 int changes = 0;
5130 boolean kept = true;
5131
Riddle Hsua0022cd2019-09-09 21:12:41 +08005132 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005133 try {
5134 if (values != null) {
5135 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5136 deferResume);
5137 }
5138
5139 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5140 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005141 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005142 }
5143
5144 if (result != null) {
5145 result.changes = changes;
5146 result.activityRelaunched = !kept;
5147 }
5148 return kept;
5149 }
5150
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005151 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005152 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005153 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005154
5155 final ActivityDisplay defaultDisplay =
5156 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5157
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005158 mTempConfig.setTo(getGlobalConfiguration());
5159 final int changes = mTempConfig.updateFrom(values);
5160 if (changes == 0) {
5161 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5162 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5163 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5164 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005165 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005166 return 0;
5167 }
5168
5169 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5170 "Updating global configuration to: " + values);
5171
5172 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5173 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5174 values.colorMode,
5175 values.densityDpi,
5176 values.fontScale,
5177 values.hardKeyboardHidden,
5178 values.keyboard,
5179 values.keyboardHidden,
5180 values.mcc,
5181 values.mnc,
5182 values.navigation,
5183 values.navigationHidden,
5184 values.orientation,
5185 values.screenHeightDp,
5186 values.screenLayout,
5187 values.screenWidthDp,
5188 values.smallestScreenWidthDp,
5189 values.touchscreen,
5190 values.uiMode);
5191
5192
5193 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5194 final LocaleList locales = values.getLocales();
5195 int bestLocaleIndex = 0;
5196 if (locales.size() > 1) {
5197 if (mSupportedSystemLocales == null) {
5198 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5199 }
5200 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5201 }
5202 SystemProperties.set("persist.sys.locale",
5203 locales.get(bestLocaleIndex).toLanguageTag());
5204 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005205
5206 final Message m = PooledLambda.obtainMessage(
5207 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5208 locales.get(bestLocaleIndex));
5209 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 }
5211
Yunfan Chen75157d72018-07-27 14:47:21 +09005212 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213
5214 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005215 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216
5217 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5218 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005219 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220
5221 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005222 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223
5224 AttributeCache ac = AttributeCache.instance();
5225 if (ac != null) {
5226 ac.updateConfiguration(mTempConfig);
5227 }
5228
5229 // Make sure all resources in our process are updated right now, so that anyone who is going
5230 // to retrieve resource values after we return will be sure to get the new ones. This is
5231 // especially important during boot, where the first config change needs to guarantee all
5232 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005233 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234
5235 // We need another copy of global config because we're scheduling some calls instead of
5236 // running them in place. We need to be sure that object we send will be handled unchanged.
5237 final Configuration configCopy = new Configuration(mTempConfig);
5238 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005239 final Message msg = PooledLambda.obtainMessage(
5240 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5241 this, userId, configCopy);
5242 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005243 }
5244
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005245 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5246 for (int i = pidMap.size() - 1; i >= 0; i--) {
5247 final int pid = pidMap.keyAt(i);
5248 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005249 if (DEBUG_CONFIGURATION) {
5250 Slog.v(TAG_CONFIGURATION, "Update process config of "
5251 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005252 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005253 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005254 }
5255
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005256 final Message msg = PooledLambda.obtainMessage(
5257 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5258 mAmInternal, changes, initLocale);
5259 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005260
5261 // Override configuration of the default display duplicates global config, so we need to
5262 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005263 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5264 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265
5266 return changes;
5267 }
5268
Riddle Hsua0022cd2019-09-09 21:12:41 +08005269 /** @see WindowSurfacePlacer#deferLayout */
5270 void deferWindowLayout() {
5271 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5272 // Reset the reasons at the first entrance because we only care about the changes in the
5273 // deferred scope.
5274 mLayoutReasons = 0;
5275 }
5276
5277 mWindowManager.mWindowPlacerLocked.deferLayout();
5278 }
5279
5280 /** @see WindowSurfacePlacer#continueLayout */
5281 void continueWindowLayout() {
5282 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5283 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5284 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5285 }
5286 }
5287
5288 /**
5289 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5290 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5291 * defer count is gone.
5292 */
5293 void addWindowLayoutReasons(@LayoutReason int reasons) {
5294 mLayoutReasons |= reasons;
5295 }
5296
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 private void updateEventDispatchingLocked(boolean booted) {
5298 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5299 }
5300
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005301 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5302 final ContentResolver resolver = mContext.getContentResolver();
5303 Settings.System.putConfigurationForUser(resolver, config, userId);
5304 }
5305
5306 private void sendLocaleToMountDaemonMsg(Locale l) {
5307 try {
5308 IBinder service = ServiceManager.getService("mount");
5309 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5310 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5311 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5312 } catch (RemoteException e) {
5313 Log.e(TAG, "Error storing locale for decryption UI", e);
5314 }
5315 }
5316
Alison Cichowlas3e340502018-08-07 17:15:01 -04005317 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5318 mStartActivitySources.remove(permissionToken);
5319 mExpiredStartAsCallerTokens.add(permissionToken);
5320 }
5321
5322 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5323 mExpiredStartAsCallerTokens.remove(permissionToken);
5324 }
5325
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005326 boolean isActivityStartsLoggingEnabled() {
5327 return mAmInternal.isActivityStartsLoggingEnabled();
5328 }
5329
Michal Karpinski8596ded2018-11-14 14:43:48 +00005330 boolean isBackgroundActivityStartsEnabled() {
5331 return mAmInternal.isBackgroundActivityStartsEnabled();
5332 }
5333
Wale Ogunwalef6733932018-06-27 05:14:34 -07005334 void enableScreenAfterBoot(boolean booted) {
5335 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5336 SystemClock.uptimeMillis());
5337 mWindowManager.enableScreenAfterBoot();
5338
5339 synchronized (mGlobalLock) {
5340 updateEventDispatchingLocked(booted);
5341 }
5342 }
5343
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005344 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5345 if (r == null || !r.hasProcess()) {
5346 return KEY_DISPATCHING_TIMEOUT_MS;
5347 }
5348 return getInputDispatchingTimeoutLocked(r.app);
5349 }
5350
5351 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005352 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005353 }
5354
Wale Ogunwalef6733932018-06-27 05:14:34 -07005355 /**
5356 * Decide based on the configuration whether we should show the ANR,
5357 * crash, etc dialogs. The idea is that if there is no affordance to
5358 * press the on-screen buttons, or the user experience would be more
5359 * greatly impacted than the crash itself, we shouldn't show the dialog.
5360 *
5361 * A thought: SystemUI might also want to get told about this, the Power
5362 * dialog / global actions also might want different behaviors.
5363 */
5364 private void updateShouldShowDialogsLocked(Configuration config) {
5365 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5366 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5367 && config.navigation == Configuration.NAVIGATION_NONAV);
5368 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5369 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5370 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5371 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5372 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5373 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5374 HIDE_ERROR_DIALOGS, 0) != 0;
5375 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5376 }
5377
5378 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5379 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5380 FONT_SCALE, 1.0f, userId);
5381
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005382 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005383 if (getGlobalConfiguration().fontScale == scaleFactor) {
5384 return;
5385 }
5386
5387 final Configuration configuration
5388 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5389 configuration.fontScale = scaleFactor;
5390 updatePersistentConfiguration(configuration, userId);
5391 }
5392 }
5393
5394 // Actually is sleeping or shutting down or whatever else in the future
5395 // is an inactive state.
5396 boolean isSleepingOrShuttingDownLocked() {
5397 return isSleepingLocked() || mShuttingDown;
5398 }
5399
5400 boolean isSleepingLocked() {
5401 return mSleeping;
5402 }
5403
Riddle Hsu16567132018-08-16 21:37:47 +08005404 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005405 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005406 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005407 if (task.isActivityTypeStandard()) {
5408 if (mCurAppTimeTracker != r.appTimeTracker) {
5409 // We are switching app tracking. Complete the current one.
5410 if (mCurAppTimeTracker != null) {
5411 mCurAppTimeTracker.stop();
5412 mH.obtainMessage(
5413 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005414 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005415 mCurAppTimeTracker = null;
5416 }
5417 if (r.appTimeTracker != null) {
5418 mCurAppTimeTracker = r.appTimeTracker;
5419 startTimeTrackingFocusedActivityLocked();
5420 }
5421 } else {
5422 startTimeTrackingFocusedActivityLocked();
5423 }
5424 } else {
5425 r.appTimeTracker = null;
5426 }
5427 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5428 // TODO: Probably not, because we don't want to resume voice on switching
5429 // back to this activity
5430 if (task.voiceInteractor != null) {
5431 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5432 } else {
5433 finishRunningVoiceLocked();
5434
5435 if (mLastResumedActivity != null) {
5436 final IVoiceInteractionSession session;
5437
Louis Changcdec0802019-11-11 11:45:07 +08005438 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005439 if (lastResumedActivityTask != null
5440 && lastResumedActivityTask.voiceSession != null) {
5441 session = lastResumedActivityTask.voiceSession;
5442 } else {
5443 session = mLastResumedActivity.voiceSession;
5444 }
5445
5446 if (session != null) {
5447 // We had been in a voice interaction session, but now focused has
5448 // move to something different. Just finish the session, we can't
5449 // return to it and retain the proper state and synchronization with
5450 // the voice interaction service.
5451 finishVoiceTask(session);
5452 }
5453 }
5454 }
5455
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005456 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5457 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 }
5459 updateResumedAppTrace(r);
5460 mLastResumedActivity = r;
5461
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005462 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463
5464 applyUpdateLockStateLocked(r);
5465 applyUpdateVrModeLocked(r);
5466
5467 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005468 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 r == null ? "NULL" : r.shortComponentName,
5470 reason);
5471 }
5472
5473 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5474 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005475 final ActivityTaskManagerInternal.SleepToken token =
5476 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005477 updateSleepIfNeededLocked();
5478 return token;
5479 }
5480 }
5481
5482 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005483 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005484 final boolean wasSleeping = mSleeping;
5485 boolean updateOomAdj = false;
5486
5487 if (!shouldSleep) {
5488 // If wasSleeping is true, we need to wake up activity manager state from when
5489 // we started sleeping. In either case, we need to apply the sleep tokens, which
5490 // will wake up stacks or put them to sleep as appropriate.
5491 if (wasSleeping) {
5492 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005493 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5494 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005495 startTimeTrackingFocusedActivityLocked();
5496 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005497 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005498 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5499 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005500 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005501 if (wasSleeping) {
5502 updateOomAdj = true;
5503 }
5504 } else if (!mSleeping && shouldSleep) {
5505 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005506 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5507 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 if (mCurAppTimeTracker != null) {
5509 mCurAppTimeTracker.stop();
5510 }
5511 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005512 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513 mStackSupervisor.goingToSleepLocked();
5514 updateResumedAppTrace(null /* resumed */);
5515 updateOomAdj = true;
5516 }
5517 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005518 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005519 }
5520 }
5521
5522 void updateOomAdj() {
5523 mH.post(mAmInternal::updateOomAdj);
5524 }
5525
Wale Ogunwale53783742018-09-16 10:21:51 -07005526 void updateCpuStats() {
5527 mH.post(mAmInternal::updateCpuStats);
5528 }
5529
Hui Yu03d12402018-12-06 18:00:37 -08005530 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5531 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005532 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5533 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005534 mH.sendMessage(m);
5535 }
5536
Hui Yu03d12402018-12-06 18:00:37 -08005537 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005538 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005539 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005540 if (task != null) {
5541 final ActivityRecord rootActivity = task.getRootActivity();
5542 if (rootActivity != null) {
5543 taskRoot = rootActivity.mActivityComponent;
5544 }
5545 }
5546
Hui Yu03d12402018-12-06 18:00:37 -08005547 final Message m = PooledLambda.obtainMessage(
5548 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005549 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005550 mH.sendMessage(m);
5551 }
5552
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005553 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5554 String hostingType) {
5555 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005556 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5557 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005558 + activity.processName);
5559 }
5560 // Post message to start process to avoid possible deadlock of calling into AMS with the
5561 // ATMS lock held.
5562 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5563 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5564 isTop, hostingType, activity.intent.getComponent());
5565 mH.sendMessage(m);
5566 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005567 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005568 }
5569 }
5570
Wale Ogunwale53783742018-09-16 10:21:51 -07005571 void setBooting(boolean booting) {
5572 mAmInternal.setBooting(booting);
5573 }
5574
5575 boolean isBooting() {
5576 return mAmInternal.isBooting();
5577 }
5578
5579 void setBooted(boolean booted) {
5580 mAmInternal.setBooted(booted);
5581 }
5582
5583 boolean isBooted() {
5584 return mAmInternal.isBooted();
5585 }
5586
5587 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5588 mH.post(() -> {
5589 if (finishBooting) {
5590 mAmInternal.finishBooting();
5591 }
5592 if (enableScreen) {
5593 mInternal.enableScreenAfterBoot(isBooted());
5594 }
5595 });
5596 }
5597
5598 void setHeavyWeightProcess(ActivityRecord root) {
5599 mHeavyWeightProcess = root.app;
5600 final Message m = PooledLambda.obtainMessage(
5601 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005602 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005603 mH.sendMessage(m);
5604 }
5605
5606 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5607 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5608 return;
5609 }
5610
5611 mHeavyWeightProcess = null;
5612 final Message m = PooledLambda.obtainMessage(
5613 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5614 proc.mUserId);
5615 mH.sendMessage(m);
5616 }
5617
5618 private void cancelHeavyWeightProcessNotification(int userId) {
5619 final INotificationManager inm = NotificationManager.getService();
5620 if (inm == null) {
5621 return;
5622 }
5623 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005624 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005625 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5626 } catch (RuntimeException e) {
5627 Slog.w(TAG, "Error canceling notification for service", e);
5628 } catch (RemoteException e) {
5629 }
5630
5631 }
5632
5633 private void postHeavyWeightProcessNotification(
5634 WindowProcessController proc, Intent intent, int userId) {
5635 if (proc == null) {
5636 return;
5637 }
5638
5639 final INotificationManager inm = NotificationManager.getService();
5640 if (inm == null) {
5641 return;
5642 }
5643
5644 try {
5645 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5646 String text = mContext.getString(R.string.heavy_weight_notification,
5647 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5648 Notification notification =
5649 new Notification.Builder(context,
5650 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5651 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5652 .setWhen(0)
5653 .setOngoing(true)
5654 .setTicker(text)
5655 .setColor(mContext.getColor(
5656 com.android.internal.R.color.system_notification_accent_color))
5657 .setContentTitle(text)
5658 .setContentText(
5659 mContext.getText(R.string.heavy_weight_notification_detail))
5660 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5661 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5662 new UserHandle(userId)))
5663 .build();
5664 try {
5665 inm.enqueueNotificationWithTag("android", "android", null,
5666 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5667 } catch (RuntimeException e) {
5668 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5669 } catch (RemoteException e) {
5670 }
5671 } catch (PackageManager.NameNotFoundException e) {
5672 Slog.w(TAG, "Unable to create context for heavy notification", e);
5673 }
5674
5675 }
5676
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005677 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5678 IBinder token, String resultWho, int requestCode, Intent[] intents,
5679 String[] resolvedTypes, int flags, Bundle bOptions) {
5680
5681 ActivityRecord activity = null;
5682 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5683 activity = ActivityRecord.isInStackLocked(token);
5684 if (activity == null) {
5685 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5686 return null;
5687 }
5688 if (activity.finishing) {
5689 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5690 return null;
5691 }
5692 }
5693
5694 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5695 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5696 bOptions);
5697 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5698 if (noCreate) {
5699 return rec;
5700 }
5701 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5702 if (activity.pendingResults == null) {
5703 activity.pendingResults = new HashSet<>();
5704 }
5705 activity.pendingResults.add(rec.ref);
5706 }
5707 return rec;
5708 }
5709
Andrii Kulian52d255c2018-07-13 11:32:19 -07005710 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005711 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005712 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005713 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5714 mCurAppTimeTracker.start(resumedActivity.packageName);
5715 }
5716 }
5717
5718 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5719 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005720 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005721 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5722 }
5723 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005724 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005725 constructResumedTraceName(resumed.packageName), 0);
5726 }
5727 mTracedResumedActivity = resumed;
5728 }
5729
5730 private String constructResumedTraceName(String packageName) {
5731 return "focused app: " + packageName;
5732 }
5733
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005734 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005735 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005736 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005737 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005738 // mainStack is null during startup.
5739 if (mainStack != null) {
5740 if (changes != 0 && starting == null) {
5741 // If the configuration changed, and the caller is not already
5742 // in the process of starting an activity, then find the top
5743 // activity to check if its configuration needs to change.
5744 starting = mainStack.topRunningActivityLocked();
5745 }
5746
5747 if (starting != null) {
5748 kept = starting.ensureActivityConfiguration(changes,
5749 false /* preserveWindow */);
5750 // And we need to make sure at this point that all other activities
5751 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005752 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005753 !PRESERVE_WINDOWS);
5754 }
5755 }
5756
5757 return kept;
5758 }
5759
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005760 void scheduleAppGcsLocked() {
5761 mH.post(() -> mAmInternal.scheduleAppGcs());
5762 }
5763
Wale Ogunwale53783742018-09-16 10:21:51 -07005764 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5765 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5766 }
5767
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005768 /**
5769 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5770 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5771 * on demand.
5772 */
5773 IPackageManager getPackageManager() {
5774 return AppGlobals.getPackageManager();
5775 }
5776
5777 PackageManagerInternal getPackageManagerInternalLocked() {
5778 if (mPmInternal == null) {
5779 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5780 }
5781 return mPmInternal;
5782 }
5783
Hai Zhangf4da9be2019-05-01 13:46:06 +08005784 PermissionPolicyInternal getPermissionPolicyInternal() {
5785 if (mPermissionPolicyInternal == null) {
5786 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5787 }
5788 return mPermissionPolicyInternal;
5789 }
5790
Wale Ogunwale008163e2018-07-23 23:11:08 -07005791 AppWarnings getAppWarningsLocked() {
5792 return mAppWarnings;
5793 }
5794
Wale Ogunwale214f3482018-10-04 11:00:47 -07005795 Intent getHomeIntent() {
5796 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5797 intent.setComponent(mTopComponent);
5798 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5799 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5800 intent.addCategory(Intent.CATEGORY_HOME);
5801 }
5802 return intent;
5803 }
5804
Chilun2ef71f72018-11-16 17:57:15 +08005805 /**
5806 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5807 * activities.
5808 *
5809 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5810 * component defined in config_secondaryHomeComponent.
5811 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5812 */
5813 Intent getSecondaryHomeIntent(String preferredPackage) {
5814 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005815 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5816 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5817 if (preferredPackage == null || useSystemProvidedLauncher) {
5818 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005819 final String secondaryHomeComponent = mContext.getResources().getString(
5820 com.android.internal.R.string.config_secondaryHomeComponent);
5821 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5822 } else {
5823 intent.setPackage(preferredPackage);
5824 }
5825 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5826 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5827 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5828 }
5829 return intent;
5830 }
5831
Wale Ogunwale214f3482018-10-04 11:00:47 -07005832 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5833 if (info == null) return null;
5834 ApplicationInfo newInfo = new ApplicationInfo(info);
5835 newInfo.initForUser(userId);
5836 return newInfo;
5837 }
5838
Wale Ogunwale9c103022018-10-18 07:44:54 -07005839 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005840 if (uid == SYSTEM_UID) {
5841 // The system gets to run in any process. If there are multiple processes with the same
5842 // uid, just pick the first (this should never happen).
5843 final SparseArray<WindowProcessController> procs =
5844 mProcessNames.getMap().get(processName);
5845 if (procs == null) return null;
5846 final int procCount = procs.size();
5847 for (int i = 0; i < procCount; i++) {
5848 final int procUid = procs.keyAt(i);
5849 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5850 // Don't use an app process or different user process for system component.
5851 continue;
5852 }
5853 return procs.valueAt(i);
5854 }
5855 }
5856
5857 return mProcessNames.get(processName, uid);
5858 }
5859
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005860 WindowProcessController getProcessController(IApplicationThread thread) {
5861 if (thread == null) {
5862 return null;
5863 }
5864
5865 final IBinder threadBinder = thread.asBinder();
5866 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5867 for (int i = pmap.size()-1; i >= 0; i--) {
5868 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5869 for (int j = procs.size() - 1; j >= 0; j--) {
5870 final WindowProcessController proc = procs.valueAt(j);
5871 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5872 return proc;
5873 }
5874 }
5875 }
5876
5877 return null;
5878 }
5879
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005880 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005881 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005882 if (proc == null) return null;
5883 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5884 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005885 }
5886 return null;
5887 }
5888
Riddle Hsua0536432019-02-16 00:38:59 +08005889 int getUidState(int uid) {
5890 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005891 }
5892
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005893 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005894 // A uid is considered to be foreground if it has a visible non-toast window.
5895 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005896 }
5897
Ricky Wai96f5c352019-04-10 18:40:17 +01005898 boolean isDeviceOwner(int uid) {
5899 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005900 }
5901
Ricky Wai96f5c352019-04-10 18:40:17 +01005902 void setDeviceOwnerUid(int uid) {
5903 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005904 }
5905
Wale Ogunwale9de19442018-10-18 19:05:03 -07005906 /**
5907 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5908 * the whitelist
5909 */
5910 String getPendingTempWhitelistTagForUidLocked(int uid) {
5911 return mPendingTempWhitelist.get(uid);
5912 }
5913
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005914 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5915 if (true || Build.IS_USER) {
5916 return;
5917 }
5918
5919 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5920 StrictMode.allowThreadDiskWrites();
5921 try {
5922 File tracesDir = new File("/data/anr");
5923 File tracesFile = null;
5924 try {
5925 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5926
5927 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005928 String timeString =
5929 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5930 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005931 sb.append(": ");
5932 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5933 sb.append(" since ");
5934 sb.append(msg);
5935 FileOutputStream fos = new FileOutputStream(tracesFile);
5936 fos.write(sb.toString().getBytes());
5937 if (app == null) {
5938 fos.write("\n*** No application process!".getBytes());
5939 }
5940 fos.close();
5941 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5942 } catch (IOException e) {
5943 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5944 return;
5945 }
5946
5947 if (app != null && app.getPid() > 0) {
5948 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5949 firstPids.add(app.getPid());
5950 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5951 }
5952
5953 File lastTracesFile = null;
5954 File curTracesFile = null;
5955 for (int i=9; i>=0; i--) {
5956 String name = String.format(Locale.US, "slow%02d.txt", i);
5957 curTracesFile = new File(tracesDir, name);
5958 if (curTracesFile.exists()) {
5959 if (lastTracesFile != null) {
5960 curTracesFile.renameTo(lastTracesFile);
5961 } else {
5962 curTracesFile.delete();
5963 }
5964 }
5965 lastTracesFile = curTracesFile;
5966 }
5967 tracesFile.renameTo(curTracesFile);
5968 } finally {
5969 StrictMode.setThreadPolicy(oldPolicy);
5970 }
5971 }
5972
Michal Karpinskida34cd42019-04-02 19:46:52 +01005973 boolean isAssociatedCompanionApp(int userId, int uid) {
5974 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5975 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005976 return false;
5977 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005978 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005979 }
5980
Issei Suzuki734bc942019-06-05 13:59:52 +02005981 void notifySingleTaskDisplayEmpty(int displayId) {
5982 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5983 }
5984
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005985 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005986 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005987
5988
Wale Ogunwale98875612018-10-12 07:53:02 -07005989 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5990 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005991
Riddle Hsud93a6c42018-11-29 21:50:06 +08005992 H(Looper looper) {
5993 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005994 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005995
5996 @Override
5997 public void handleMessage(Message msg) {
5998 switch (msg.what) {
5999 case REPORT_TIME_TRACKER_MSG: {
6000 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6001 tracker.deliverResult(mContext);
6002 } break;
6003 }
6004 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006005 }
6006
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006007 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006008 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006009
6010 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006011 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006013
6014 @Override
6015 public void handleMessage(Message msg) {
6016 switch (msg.what) {
6017 case DISMISS_DIALOG_UI_MSG: {
6018 final Dialog d = (Dialog) msg.obj;
6019 d.dismiss();
6020 break;
6021 }
6022 }
6023 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006024 }
6025
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006026 final class LocalService extends ActivityTaskManagerInternal {
6027 @Override
6028 public SleepToken acquireSleepToken(String tag, int displayId) {
6029 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006030 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 }
6032
6033 @Override
6034 public ComponentName getHomeActivityForUser(int userId) {
6035 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006036 final ActivityRecord homeActivity =
6037 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006038 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 }
6040 }
6041
6042 @Override
6043 public void onLocalVoiceInteractionStarted(IBinder activity,
6044 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6045 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006046 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006047 }
6048 }
6049
6050 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006051 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006052 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006053 synchronized (mGlobalLock) {
6054 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006055 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 }
6057 }
6058
6059 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006060 public void notifySingleTaskDisplayDrawn(int displayId) {
6061 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6062 }
6063
6064 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006065 public void notifyAppTransitionFinished() {
6066 synchronized (mGlobalLock) {
6067 mStackSupervisor.notifyAppTransitionDone();
6068 }
6069 }
6070
6071 @Override
6072 public void notifyAppTransitionCancelled() {
6073 synchronized (mGlobalLock) {
6074 mStackSupervisor.notifyAppTransitionDone();
6075 }
6076 }
6077
6078 @Override
6079 public List<IBinder> getTopVisibleActivities() {
6080 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006081 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006082 }
6083 }
6084
6085 @Override
6086 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6087 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006088 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006089 }
6090 }
6091
6092 @Override
6093 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6094 Bundle bOptions) {
6095 Preconditions.checkNotNull(intents, "intents");
6096 final String[] resolvedTypes = new String[intents.length];
6097
6098 // UID of the package on user userId.
6099 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6100 // packageUid may not be initialized.
6101 int packageUid = 0;
6102 final long ident = Binder.clearCallingIdentity();
6103
6104 try {
6105 for (int i = 0; i < intents.length; i++) {
6106 resolvedTypes[i] =
6107 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6108 }
6109
6110 packageUid = AppGlobals.getPackageManager().getPackageUid(
6111 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6112 } catch (RemoteException e) {
6113 // Shouldn't happen.
6114 } finally {
6115 Binder.restoreCallingIdentity(ident);
6116 }
6117
Riddle Hsu591bf612019-02-14 17:55:31 +08006118 return getActivityStartController().startActivitiesInPackage(
6119 packageUid, packageName,
6120 intents, resolvedTypes, null /* resultTo */,
6121 SafeActivityOptions.fromBundle(bOptions), userId,
6122 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6123 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006124 }
6125
6126 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006127 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6128 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6129 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6130 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006131 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006132 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006133 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6134 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6135 userId, validateIncomingUser, originatingPendingIntent,
6136 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006137 }
6138 }
6139
6140 @Override
6141 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6142 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6143 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006144 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006145 PendingIntentRecord originatingPendingIntent,
6146 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006147 synchronized (mGlobalLock) {
6148 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6149 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6150 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006151 validateIncomingUser, originatingPendingIntent,
6152 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006153 }
6154 }
6155
6156 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6158 Intent intent, Bundle options, int userId) {
6159 return ActivityTaskManagerService.this.startActivityAsUser(
6160 caller, callerPacakge, intent,
6161 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6162 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6163 false /*validateIncomingUser*/);
6164 }
6165
6166 @Override
lumark588a3e82018-07-20 18:53:54 +08006167 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 synchronized (mGlobalLock) {
6169
6170 // We might change the visibilities here, so prepare an empty app transition which
6171 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006172 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006173 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006174 if (activityDisplay == null) {
6175 return;
6176 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006177 final DisplayContent dc = activityDisplay.mDisplayContent;
6178 final boolean wasTransitionSet =
6179 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006180 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006181 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006183 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006184
6185 // If there was a transition set already we don't want to interfere with it as we
6186 // might be starting it too early.
6187 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006188 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 }
6190 }
6191 if (callback != null) {
6192 callback.run();
6193 }
6194 }
6195
6196 @Override
6197 public void notifyKeyguardTrustedChanged() {
6198 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006199 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006200 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006201 }
6202 }
6203 }
6204
6205 /**
6206 * Called after virtual display Id is updated by
6207 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6208 * {@param vrVr2dDisplayId}.
6209 */
6210 @Override
6211 public void setVr2dDisplayId(int vr2dDisplayId) {
6212 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6213 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006214 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006215 }
6216 }
6217
6218 @Override
6219 public void setFocusedActivity(IBinder token) {
6220 synchronized (mGlobalLock) {
6221 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6222 if (r == null) {
6223 throw new IllegalArgumentException(
6224 "setFocusedActivity: No activity record matching token=" + token);
6225 }
Louis Chang19443452018-10-09 12:10:21 +08006226 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006227 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006228 }
6229 }
6230 }
6231
6232 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006234 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235 }
6236
6237 @Override
6238 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006239 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 }
6241
6242 @Override
6243 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006244 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006245 }
6246
6247 @Override
6248 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6249 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6250 }
6251
6252 @Override
6253 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006254 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006255 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006256
6257 @Override
6258 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6259 synchronized (mGlobalLock) {
6260 mActiveVoiceInteractionServiceComponent = component;
6261 }
6262 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006263
6264 @Override
6265 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6266 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6267 return;
6268 }
6269 synchronized (mGlobalLock) {
6270 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6271 if (types == null) {
6272 if (uid < 0) {
6273 return;
6274 }
6275 types = new ArrayMap<>();
6276 mAllowAppSwitchUids.put(userId, types);
6277 }
6278 if (uid < 0) {
6279 types.remove(type);
6280 } else {
6281 types.put(type, uid);
6282 }
6283 }
6284 }
6285
6286 @Override
6287 public void onUserStopped(int userId) {
6288 synchronized (mGlobalLock) {
6289 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6290 mAllowAppSwitchUids.remove(userId);
6291 }
6292 }
6293
6294 @Override
6295 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6296 synchronized (mGlobalLock) {
6297 return ActivityTaskManagerService.this.isGetTasksAllowed(
6298 caller, callingPid, callingUid);
6299 }
6300 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006301
Riddle Hsua0536432019-02-16 00:38:59 +08006302 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006303 @Override
6304 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006306 mProcessNames.put(proc.mName, proc.mUid, proc);
6307 }
6308 }
6309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006311 @Override
6312 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006314 mProcessNames.remove(name, uid);
6315 }
6316 }
6317
Riddle Hsua0536432019-02-16 00:38:59 +08006318 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006319 @Override
6320 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006321 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006322 if (proc == mHomeProcess) {
6323 mHomeProcess = null;
6324 }
6325 if (proc == mPreviousProcess) {
6326 mPreviousProcess = null;
6327 }
6328 }
6329 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006330
Riddle Hsua0536432019-02-16 00:38:59 +08006331 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006332 @Override
6333 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006334 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006335 return mTopProcessState;
6336 }
6337 }
6338
Riddle Hsua0536432019-02-16 00:38:59 +08006339 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006340 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006341 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006342 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006343 return proc == mHeavyWeightProcess;
6344 }
6345 }
6346
Riddle Hsua0536432019-02-16 00:38:59 +08006347 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006348 @Override
6349 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006350 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006351 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6352 }
6353 }
6354
6355 @Override
6356 public void finishHeavyWeightApp() {
6357 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006358 if (mHeavyWeightProcess != null) {
6359 mHeavyWeightProcess.finishActivities();
6360 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006361 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6362 mHeavyWeightProcess);
6363 }
6364 }
6365
Riddle Hsua0536432019-02-16 00:38:59 +08006366 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006367 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006368 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006369 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006370 return isSleepingLocked();
6371 }
6372 }
6373
6374 @Override
6375 public boolean isShuttingDown() {
6376 synchronized (mGlobalLock) {
6377 return mShuttingDown;
6378 }
6379 }
6380
6381 @Override
6382 public boolean shuttingDown(boolean booted, int timeout) {
6383 synchronized (mGlobalLock) {
6384 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006385 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006386 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006387 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006388 return mStackSupervisor.shutdownLocked(timeout);
6389 }
6390 }
6391
6392 @Override
6393 public void enableScreenAfterBoot(boolean booted) {
6394 synchronized (mGlobalLock) {
6395 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6396 SystemClock.uptimeMillis());
6397 mWindowManager.enableScreenAfterBoot();
6398 updateEventDispatchingLocked(booted);
6399 }
6400 }
6401
6402 @Override
6403 public boolean showStrictModeViolationDialog() {
6404 synchronized (mGlobalLock) {
6405 return mShowDialogs && !mSleeping && !mShuttingDown;
6406 }
6407 }
6408
6409 @Override
6410 public void showSystemReadyErrorDialogsIfNeeded() {
6411 synchronized (mGlobalLock) {
6412 try {
6413 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6414 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6415 + " data partition or your device will be unstable.");
6416 mUiHandler.post(() -> {
6417 if (mShowDialogs) {
6418 AlertDialog d = new BaseErrorDialog(mUiContext);
6419 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6420 d.setCancelable(false);
6421 d.setTitle(mUiContext.getText(R.string.android_system_label));
6422 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6423 d.setButton(DialogInterface.BUTTON_POSITIVE,
6424 mUiContext.getText(R.string.ok),
6425 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6426 d.show();
6427 }
6428 });
6429 }
6430 } catch (RemoteException e) {
6431 }
6432
6433 if (!Build.isBuildConsistent()) {
6434 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6435 mUiHandler.post(() -> {
6436 if (mShowDialogs) {
6437 AlertDialog d = new BaseErrorDialog(mUiContext);
6438 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6439 d.setCancelable(false);
6440 d.setTitle(mUiContext.getText(R.string.android_system_label));
6441 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6442 d.setButton(DialogInterface.BUTTON_POSITIVE,
6443 mUiContext.getText(R.string.ok),
6444 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6445 d.show();
6446 }
6447 });
6448 }
6449 }
6450 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006451
6452 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006453 public void onProcessMapped(int pid, WindowProcessController proc) {
6454 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006455 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006456 }
6457 }
6458
6459 @Override
6460 public void onProcessUnMapped(int pid) {
6461 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006462 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006463 }
6464 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006465
6466 @Override
6467 public void onPackageDataCleared(String name) {
6468 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006469 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006470 mAppWarnings.onPackageDataCleared(name);
6471 }
6472 }
6473
6474 @Override
6475 public void onPackageUninstalled(String name) {
6476 synchronized (mGlobalLock) {
6477 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006478 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006479 }
6480 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006481
6482 @Override
6483 public void onPackageAdded(String name, boolean replacing) {
6484 synchronized (mGlobalLock) {
6485 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6486 }
6487 }
6488
6489 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006490 public void onPackageReplaced(ApplicationInfo aInfo) {
6491 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006492 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006493 }
6494 }
6495
6496 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006497 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6498 synchronized (mGlobalLock) {
6499 return compatibilityInfoForPackageLocked(ai);
6500 }
6501 }
6502
Yunfan Chen75157d72018-07-27 14:47:21 +09006503 /**
6504 * Set the corresponding display information for the process global configuration. To be
6505 * called when we need to show IME on a different display.
6506 *
6507 * @param pid The process id associated with the IME window.
6508 * @param displayId The ID of the display showing the IME.
6509 */
6510 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006511 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006512 // Don't update process-level configuration for Multi-Client IME process since other
6513 // IMEs on other displays will also receive this configuration change due to IME
6514 // services use the same application config/context.
6515 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006516
Yunfan Chen75157d72018-07-27 14:47:21 +09006517 if (pid == MY_PID || pid < 0) {
6518 if (DEBUG_CONFIGURATION) {
6519 Slog.w(TAG,
6520 "Trying to update display configuration for system/invalid process.");
6521 }
6522 return;
6523 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006524 synchronized (mGlobalLock) {
6525 final ActivityDisplay activityDisplay =
6526 mRootActivityContainer.getActivityDisplay(displayId);
6527 if (activityDisplay == null) {
6528 // Call might come when display is not yet added or has been removed.
6529 if (DEBUG_CONFIGURATION) {
6530 Slog.w(TAG, "Trying to update display configuration for non-existing "
6531 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006532 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006533 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006534 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006535 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006536 if (process == null) {
6537 if (DEBUG_CONFIGURATION) {
6538 Slog.w(TAG, "Trying to update display configuration for invalid "
6539 + "process, pid=" + pid);
6540 }
6541 return;
6542 }
lumarkddc77fb2019-06-27 22:22:23 +08006543 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006544 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6545 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006546 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006547
6548 @Override
6549 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006550 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006551 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006552 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6553 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006554 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006555 }
6556 }
6557 }
6558
6559 @Override
6560 public void clearPendingResultForActivity(IBinder activityToken,
6561 WeakReference<PendingIntentRecord> pir) {
6562 synchronized (mGlobalLock) {
6563 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6564 if (r != null && r.pendingResults != null) {
6565 r.pendingResults.remove(pir);
6566 }
6567 }
6568 }
6569
6570 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006571 public ActivityTokens getTopActivityForTask(int taskId) {
6572 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006573 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6574 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006575 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6576 + " Requested task not found");
6577 return null;
6578 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006579 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006580 if (activity == null) {
6581 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6582 + " Requested activity not found");
6583 return null;
6584 }
6585 if (!activity.attachedToProcess()) {
6586 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6587 + activity);
6588 return null;
6589 }
6590 return new ActivityTokens(activity.appToken, activity.assistToken,
6591 activity.app.getThread());
6592 }
6593 }
6594
6595 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006596 public IIntentSender getIntentSender(int type, String packageName,
6597 int callingUid, int userId, IBinder token, String resultWho,
6598 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6599 Bundle bOptions) {
6600 synchronized (mGlobalLock) {
6601 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6602 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6603 }
6604 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006605
6606 @Override
6607 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6608 synchronized (mGlobalLock) {
6609 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6610 if (r == null) {
6611 return null;
6612 }
6613 if (r.mServiceConnectionsHolder == null) {
6614 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6615 ActivityTaskManagerService.this, r);
6616 }
6617
6618 return r.mServiceConnectionsHolder;
6619 }
6620 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006621
6622 @Override
6623 public Intent getHomeIntent() {
6624 synchronized (mGlobalLock) {
6625 return ActivityTaskManagerService.this.getHomeIntent();
6626 }
6627 }
6628
6629 @Override
6630 public boolean startHomeActivity(int userId, String reason) {
6631 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006632 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006633 }
6634 }
6635
6636 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006637 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006638 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006639 synchronized (mGlobalLock) {
6640 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006641 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006642 }
Chilun8b1f1be2019-03-13 17:14:36 +08006643 }
6644
6645 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006646 public boolean startHomeOnAllDisplays(int userId, String reason) {
6647 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006648 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006649 }
6650 }
6651
Riddle Hsua0536432019-02-16 00:38:59 +08006652 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006653 @Override
6654 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006655 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006656 if (mFactoryTest == FACTORY_TEST_OFF) {
6657 return false;
6658 }
6659 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6660 && wpc.mName.equals(mTopComponent.getPackageName())) {
6661 return true;
6662 }
6663 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6664 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6665 }
6666 }
6667
6668 @Override
6669 public void updateTopComponentForFactoryTest() {
6670 synchronized (mGlobalLock) {
6671 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6672 return;
6673 }
6674 final ResolveInfo ri = mContext.getPackageManager()
6675 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6676 final CharSequence errorMsg;
6677 if (ri != null) {
6678 final ActivityInfo ai = ri.activityInfo;
6679 final ApplicationInfo app = ai.applicationInfo;
6680 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6681 mTopAction = Intent.ACTION_FACTORY_TEST;
6682 mTopData = null;
6683 mTopComponent = new ComponentName(app.packageName, ai.name);
6684 errorMsg = null;
6685 } else {
6686 errorMsg = mContext.getResources().getText(
6687 com.android.internal.R.string.factorytest_not_system);
6688 }
6689 } else {
6690 errorMsg = mContext.getResources().getText(
6691 com.android.internal.R.string.factorytest_no_action);
6692 }
6693 if (errorMsg == null) {
6694 return;
6695 }
6696
6697 mTopAction = null;
6698 mTopData = null;
6699 mTopComponent = null;
6700 mUiHandler.post(() -> {
6701 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6702 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006703 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006704 });
6705 }
6706 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707
Riddle Hsua0536432019-02-16 00:38:59 +08006708 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 @Override
6710 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6711 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006712 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006714 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006715
6716 wpc.clearRecentTasks();
6717 wpc.clearActivities();
6718
6719 if (wpc.isInstrumenting()) {
6720 finishInstrumentationCallback.run();
6721 }
6722
Jorim Jaggid0752812018-10-16 16:07:20 +02006723 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006724 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006725 try {
6726 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6727 // If there was nothing to resume, and we are not already restarting
6728 // this process, but there is a visible activity that is hosted by the
6729 // process...then make sure all visible activities are running, taking
6730 // care of restarting this process.
6731 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6732 !PRESERVE_WINDOWS);
6733 }
6734 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006735 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006736 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 }
6738 }
6739 }
6740
6741 @Override
6742 public void closeSystemDialogs(String reason) {
6743 enforceNotIsolatedCaller("closeSystemDialogs");
6744
6745 final int pid = Binder.getCallingPid();
6746 final int uid = Binder.getCallingUid();
6747 final long origId = Binder.clearCallingIdentity();
6748 try {
6749 synchronized (mGlobalLock) {
6750 // Only allow this from foreground processes, so that background
6751 // applications can't abuse it to prevent system UI from being shown.
6752 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006753 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006754 if (!proc.isPerceptible()) {
6755 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6756 + " from background process " + proc);
6757 return;
6758 }
6759 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006760 mWindowManager.closeSystemDialogs(reason);
6761
Wale Ogunwaled32da472018-11-16 07:19:28 -08006762 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006764 // Call into AM outside the synchronized block.
6765 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006766 } finally {
6767 Binder.restoreCallingIdentity(origId);
6768 }
6769 }
6770
6771 @Override
6772 public void cleanupDisabledPackageComponents(
6773 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6774 synchronized (mGlobalLock) {
6775 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006776 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006778 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 mStackSupervisor.scheduleIdleLocked();
6780 }
6781
6782 // Clean-up disabled tasks
6783 getRecentTasks().cleanupDisabledPackageTasksLocked(
6784 packageName, disabledClasses, userId);
6785 }
6786 }
6787
6788 @Override
6789 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6790 int userId) {
6791 synchronized (mGlobalLock) {
6792
6793 boolean didSomething =
6794 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006795 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 null, doit, evenPersistent, userId);
6797 return didSomething;
6798 }
6799 }
6800
6801 @Override
6802 public void resumeTopActivities(boolean scheduleIdle) {
6803 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006804 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006805 if (scheduleIdle) {
6806 mStackSupervisor.scheduleIdleLocked();
6807 }
6808 }
6809 }
6810
Riddle Hsua0536432019-02-16 00:38:59 +08006811 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 @Override
6813 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006814 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006815 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6816 }
6817 }
6818
Riddle Hsua0536432019-02-16 00:38:59 +08006819 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 @Override
6821 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006822 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006823 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6824 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6825 }
6826 try {
6827 return mRootActivityContainer.attachApplication(wpc);
6828 } finally {
6829 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6830 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006831 }
6832 }
6833
6834 @Override
6835 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6836 try {
6837 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6838 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6839 }
6840 } catch (RemoteException ex) {
6841 throw new SecurityException("Fail to check is caller a privileged app", ex);
6842 }
6843
6844 synchronized (mGlobalLock) {
6845 final long ident = Binder.clearCallingIdentity();
6846 try {
6847 if (mAmInternal.shouldConfirmCredentials(userId)) {
6848 if (mKeyguardController.isKeyguardLocked()) {
6849 // Showing launcher to avoid user entering credential twice.
6850 startHomeActivity(currentUserId, "notifyLockedProfile");
6851 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006852 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 }
6854 } finally {
6855 Binder.restoreCallingIdentity(ident);
6856 }
6857 }
6858 }
6859
6860 @Override
6861 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6862 mAmInternal.enforceCallingPermission(
6863 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6864
6865 synchronized (mGlobalLock) {
6866 final long ident = Binder.clearCallingIdentity();
6867 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006868 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6869 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6872 UserHandle.CURRENT);
6873 } finally {
6874 Binder.restoreCallingIdentity(ident);
6875 }
6876 }
6877 }
6878
6879 @Override
6880 public void writeActivitiesToProto(ProtoOutputStream proto) {
6881 synchronized (mGlobalLock) {
6882 // The output proto of "activity --proto activities"
6883 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006884 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006885 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6886 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006887 }
6888 }
6889
6890 @Override
6891 public void saveANRState(String reason) {
6892 synchronized (mGlobalLock) {
6893 final StringWriter sw = new StringWriter();
6894 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6895 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6896 if (reason != null) {
6897 pw.println(" Reason: " + reason);
6898 }
6899 pw.println();
6900 getActivityStartController().dump(pw, " ", null);
6901 pw.println();
6902 pw.println("-------------------------------------------------------------------------------");
6903 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6904 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6905 "" /* header */);
6906 pw.println();
6907 pw.close();
6908
6909 mLastANRState = sw.toString();
6910 }
6911 }
6912
6913 @Override
6914 public void clearSavedANRState() {
6915 synchronized (mGlobalLock) {
6916 mLastANRState = null;
6917 }
6918 }
6919
6920 @Override
6921 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6922 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6923 synchronized (mGlobalLock) {
6924 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6925 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6926 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6927 dumpLastANRLocked(pw);
6928 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6929 dumpLastANRTracesLocked(pw);
6930 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6931 dumpActivityStarterLocked(pw, dumpPackage);
6932 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6933 dumpActivityContainersLocked(pw);
6934 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6935 if (getRecentTasks() != null) {
6936 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6937 }
6938 }
6939 }
6940 }
6941
6942 @Override
6943 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6944 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6945 int wakefulness) {
6946 synchronized (mGlobalLock) {
6947 if (mHomeProcess != null && (dumpPackage == null
6948 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6949 if (needSep) {
6950 pw.println();
6951 needSep = false;
6952 }
6953 pw.println(" mHomeProcess: " + mHomeProcess);
6954 }
6955 if (mPreviousProcess != null && (dumpPackage == null
6956 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6957 if (needSep) {
6958 pw.println();
6959 needSep = false;
6960 }
6961 pw.println(" mPreviousProcess: " + mPreviousProcess);
6962 }
6963 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6964 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6965 StringBuilder sb = new StringBuilder(128);
6966 sb.append(" mPreviousProcessVisibleTime: ");
6967 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6968 pw.println(sb);
6969 }
6970 if (mHeavyWeightProcess != null && (dumpPackage == null
6971 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6972 if (needSep) {
6973 pw.println();
6974 needSep = false;
6975 }
6976 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6977 }
6978 if (dumpPackage == null) {
6979 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006980 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006981 }
6982 if (dumpAll) {
6983 if (dumpPackage == null) {
6984 pw.println(" mConfigWillChange: "
6985 + getTopDisplayFocusedStack().mConfigWillChange);
6986 }
6987 if (mCompatModePackages.getPackages().size() > 0) {
6988 boolean printed = false;
6989 for (Map.Entry<String, Integer> entry
6990 : mCompatModePackages.getPackages().entrySet()) {
6991 String pkg = entry.getKey();
6992 int mode = entry.getValue();
6993 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6994 continue;
6995 }
6996 if (!printed) {
6997 pw.println(" mScreenCompatPackages:");
6998 printed = true;
6999 }
7000 pw.println(" " + pkg + ": " + mode);
7001 }
7002 }
7003 }
7004
7005 if (dumpPackage == null) {
7006 pw.println(" mWakefulness="
7007 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007008 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007009 if (mRunningVoice != null) {
7010 pw.println(" mRunningVoice=" + mRunningVoice);
7011 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7012 }
7013 pw.println(" mSleeping=" + mSleeping);
7014 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7015 pw.println(" mVrController=" + mVrController);
7016 }
7017 if (mCurAppTimeTracker != null) {
7018 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7019 }
7020 if (mAllowAppSwitchUids.size() > 0) {
7021 boolean printed = false;
7022 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7023 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7024 for (int j = 0; j < types.size(); j++) {
7025 if (dumpPackage == null ||
7026 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7027 if (needSep) {
7028 pw.println();
7029 needSep = false;
7030 }
7031 if (!printed) {
7032 pw.println(" mAllowAppSwitchUids:");
7033 printed = true;
7034 }
7035 pw.print(" User ");
7036 pw.print(mAllowAppSwitchUids.keyAt(i));
7037 pw.print(": Type ");
7038 pw.print(types.keyAt(j));
7039 pw.print(" = ");
7040 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7041 pw.println();
7042 }
7043 }
7044 }
7045 }
7046 if (dumpPackage == null) {
7047 if (mController != null) {
7048 pw.println(" mController=" + mController
7049 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7050 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007051 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7052 pw.println(" mLaunchingActivityWakeLock="
7053 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007054 }
7055
7056 return needSep;
7057 }
7058 }
7059
7060 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007061 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7062 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007063 synchronized (mGlobalLock) {
7064 if (dumpPackage == null) {
7065 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7066 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007067 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7068 if (mRunningVoice != null) {
7069 final long vrToken = proto.start(
7070 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7071 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7072 mRunningVoice.toString());
7073 mVoiceWakeLock.writeToProto(
7074 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7075 proto.end(vrToken);
7076 }
7077 mVrController.writeToProto(proto,
7078 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 if (mController != null) {
7080 final long token = proto.start(CONTROLLER);
7081 proto.write(CONTROLLER, mController.toString());
7082 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7083 proto.end(token);
7084 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007085 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7086 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7087 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 }
7089
7090 if (mHomeProcess != null && (dumpPackage == null
7091 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007092 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 }
7094
7095 if (mPreviousProcess != null && (dumpPackage == null
7096 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007097 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007098 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7099 }
7100
7101 if (mHeavyWeightProcess != null && (dumpPackage == null
7102 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007103 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 }
7105
7106 for (Map.Entry<String, Integer> entry
7107 : mCompatModePackages.getPackages().entrySet()) {
7108 String pkg = entry.getKey();
7109 int mode = entry.getValue();
7110 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7111 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7112 proto.write(PACKAGE, pkg);
7113 proto.write(MODE, mode);
7114 proto.end(compatToken);
7115 }
7116 }
7117
7118 if (mCurAppTimeTracker != null) {
7119 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7120 }
7121
7122 }
7123 }
7124
7125 @Override
7126 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7127 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7128 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007129 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7130 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 }
7132
7133 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007134 public void dumpForOom(PrintWriter pw) {
7135 synchronized (mGlobalLock) {
7136 pw.println(" mHomeProcess: " + mHomeProcess);
7137 pw.println(" mPreviousProcess: " + mPreviousProcess);
7138 if (mHeavyWeightProcess != null) {
7139 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7140 }
7141 }
7142 }
7143
7144 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 public boolean canGcNow() {
7146 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007147 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007148 }
7149 }
7150
Riddle Hsua0536432019-02-16 00:38:59 +08007151 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007152 @Override
7153 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007154 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007155 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 return top != null ? top.app : null;
7157 }
7158 }
7159
Riddle Hsua0536432019-02-16 00:38:59 +08007160 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 @Override
7162 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007163 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007164 if (mRootActivityContainer != null) {
7165 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007166 }
7167 }
7168 }
7169
7170 @Override
7171 public void scheduleDestroyAllActivities(String reason) {
7172 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007173 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 }
7175 }
7176
7177 @Override
7178 public void removeUser(int userId) {
7179 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007180 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007181 }
7182 }
7183
7184 @Override
7185 public boolean switchUser(int userId, UserState userState) {
7186 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007187 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 }
7189 }
7190
7191 @Override
7192 public void onHandleAppCrash(WindowProcessController wpc) {
7193 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007194 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 }
7196 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007197
7198 @Override
7199 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007201 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007202 }
7203 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007204
Riddle Hsua0536432019-02-16 00:38:59 +08007205 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007206 @Override
7207 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007208 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007209 }
7210
Riddle Hsua0536432019-02-16 00:38:59 +08007211 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007212 @Override
7213 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007214 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007215 }
7216
Riddle Hsua0536432019-02-16 00:38:59 +08007217 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007218 @Override
7219 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007220 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007221 }
7222
Riddle Hsua0536432019-02-16 00:38:59 +08007223 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007224 @Override
7225 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007226 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007227 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007228
7229 @Override
7230 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007231 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007232 mPendingTempWhitelist.put(uid, tag);
7233 }
7234 }
7235
7236 @Override
7237 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007238 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007239 mPendingTempWhitelist.remove(uid);
7240 }
7241 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007242
7243 @Override
7244 public boolean handleAppCrashInActivityController(String processName, int pid,
7245 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7246 Runnable killCrashingAppCallback) {
7247 synchronized (mGlobalLock) {
7248 if (mController == null) {
7249 return false;
7250 }
7251
7252 try {
7253 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7254 stackTrace)) {
7255 killCrashingAppCallback.run();
7256 return true;
7257 }
7258 } catch (RemoteException e) {
7259 mController = null;
7260 Watchdog.getInstance().setActivityController(null);
7261 }
7262 return false;
7263 }
7264 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007265
7266 @Override
7267 public void removeRecentTasksByPackageName(String packageName, int userId) {
7268 synchronized (mGlobalLock) {
7269 mRecentTasks.removeTasksByPackageName(packageName, userId);
7270 }
7271 }
7272
7273 @Override
7274 public void cleanupRecentTasksForUser(int userId) {
7275 synchronized (mGlobalLock) {
7276 mRecentTasks.cleanupLocked(userId);
7277 }
7278 }
7279
7280 @Override
7281 public void loadRecentTasksForUser(int userId) {
7282 synchronized (mGlobalLock) {
7283 mRecentTasks.loadUserRecentsLocked(userId);
7284 }
7285 }
7286
7287 @Override
7288 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7289 synchronized (mGlobalLock) {
7290 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7291 }
7292 }
7293
7294 @Override
7295 public void flushRecentTasks() {
7296 mRecentTasks.flush();
7297 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007298
7299 @Override
7300 public WindowProcessController getHomeProcess() {
7301 synchronized (mGlobalLock) {
7302 return mHomeProcess;
7303 }
7304 }
7305
7306 @Override
7307 public WindowProcessController getPreviousProcess() {
7308 synchronized (mGlobalLock) {
7309 return mPreviousProcess;
7310 }
7311 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007312
7313 @Override
7314 public void clearLockedTasks(String reason) {
7315 synchronized (mGlobalLock) {
7316 getLockTaskController().clearLockedTasks(reason);
7317 }
7318 }
7319
7320 @Override
7321 public void updateUserConfiguration() {
7322 synchronized (mGlobalLock) {
7323 final Configuration configuration = new Configuration(getGlobalConfiguration());
7324 final int currentUserId = mAmInternal.getCurrentUserId();
7325 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7326 configuration, currentUserId, Settings.System.canWrite(mContext));
7327 updateConfigurationLocked(configuration, null /* starting */,
7328 false /* initLocale */, false /* persistent */, currentUserId,
7329 false /* deferResume */);
7330 }
7331 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007332
7333 @Override
7334 public boolean canShowErrorDialogs() {
7335 synchronized (mGlobalLock) {
7336 return mShowDialogs && !mSleeping && !mShuttingDown
7337 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7338 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7339 mAmInternal.getCurrentUserId())
7340 && !(UserManager.isDeviceInDemoMode(mContext)
7341 && mAmInternal.getCurrentUser().isDemo());
7342 }
7343 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007344
7345 @Override
7346 public void setProfileApp(String profileApp) {
7347 synchronized (mGlobalLock) {
7348 mProfileApp = profileApp;
7349 }
7350 }
7351
7352 @Override
7353 public void setProfileProc(WindowProcessController wpc) {
7354 synchronized (mGlobalLock) {
7355 mProfileProc = wpc;
7356 }
7357 }
7358
7359 @Override
7360 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7361 synchronized (mGlobalLock) {
7362 mProfilerInfo = profilerInfo;
7363 }
7364 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007365
7366 @Override
7367 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7368 synchronized (mGlobalLock) {
7369 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7370 }
7371 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007372
7373 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007374 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7375 boolean reducedResolution) {
7376 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7377 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007378 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007379
7380 @Override
7381 public boolean isUidForeground(int uid) {
7382 synchronized (mGlobalLock) {
7383 return ActivityTaskManagerService.this.isUidForeground(uid);
7384 }
7385 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007386
7387 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007388 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007389 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007390 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007391 }
7392 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007393
7394 @Override
7395 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007396 // Translate package names into UIDs
7397 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007398 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007399 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7400 if (uid >= 0) {
7401 result.add(uid);
7402 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007403 }
7404 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007405 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007406 }
7407 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007408 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007409}