blob: ba8257257057f898511f458a1c6c1a9607af37b1 [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;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070071import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
72import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080081import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070085import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
86import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import 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;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.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 Rosky4505b352018-09-06 11:20:40 -0700229import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700266import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800268import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100315 // How long we permit background activity starts after an activity in the process
316 // started or finished.
317 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318
Wale Ogunwale98875612018-10-12 07:53:02 -0700319 /** Used to indicate that an app transition should be animated. */
320 static final boolean ANIMATE = true;
321
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700322 /** Hardware-reported OpenGLES version. */
323 final int GL_ES_VERSION;
324
Wale Ogunwale31913b52018-10-13 08:29:31 -0700325 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
326 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
327 public static final String DUMP_LASTANR_CMD = "lastanr" ;
328 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
329 public static final String DUMP_STARTER_CMD = "starter" ;
330 public static final String DUMP_CONTAINERS_CMD = "containers" ;
331 public static final String DUMP_RECENTS_CMD = "recents" ;
332 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
333
Wale Ogunwale64258362018-10-16 15:13:37 -0700334 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
335 public static final int RELAUNCH_REASON_NONE = 0;
336 /** This activity is being relaunched due to windowing mode change. */
337 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
338 /** This activity is being relaunched due to a free-resize operation. */
339 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
340
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700341 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700342
Wale Ogunwalef6733932018-06-27 05:14:34 -0700343 /**
344 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
345 * change at runtime. Use mContext for non-UI purposes.
346 */
347 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700349 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700352 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700353 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800354 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800355 @VisibleForTesting
356 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 PowerManagerInternal mPowerManagerInternal;
358 private UsageStatsManagerInternal mUsageStatsInternal;
359
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700360 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 IntentFirewall mIntentFirewall;
362
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700363 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800364 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700366 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
368 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
369 *
370 * @see WindowManagerThreadPriorityBooster
371 */
372 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700373 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800374 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700375 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700376 private UserManagerService mUserManager;
377 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700378 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800379 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700380 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** All processes currently running that might have a window organized by name. */
382 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100383 /** All processes we currently have running mapped by pid and uid */
384 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** This is the process holding what we currently consider to be the "home" activity. */
386 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700387 /** The currently running heavy-weight process, if any. */
388 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700389 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /**
391 * This is the process holding the activity the user last visited that is in a different process
392 * from the one they are currently in.
393 */
394 WindowProcessController mPreviousProcess;
395 /** The time at which the previous process was last visible. */
396 long mPreviousProcessVisibleTime;
397
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700398 /** List of intents that were used to start the most recent tasks. */
399 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700400 /** State of external calls telling us if the device is awake or asleep. */
401 private boolean mKeyguardShown = false;
402
403 // Wrapper around VoiceInteractionServiceManager
404 private AssistUtils mAssistUtils;
405
406 // VoiceInteraction session ID that changes for each new request except when
407 // being called for multi-window assist in a single session.
408 private int mViSessionId = 1000;
409
410 // How long to wait in getAssistContextExtras for the activity and foreground services
411 // to respond with the result.
412 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
413
414 // How long top wait when going through the modern assist (which doesn't need to block
415 // on getting this result before starting to launch its UI).
416 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
417
418 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
419 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
420
Alison Cichowlas3e340502018-08-07 17:15:01 -0400421 // Permission tokens are used to temporarily granted a trusted app the ability to call
422 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
423 // showing any appropriate error messages to the user.
424 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
425 10 * MINUTE_IN_MILLIS;
426
427 // How long before the service actually expires a token. This is slightly longer than
428 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
429 // expiration exception.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
431 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
432
433 // How long the service will remember expired tokens, for the purpose of providing error
434 // messaging when a client uses an expired token.
435 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
436 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
437
438 // Activity tokens of system activities that are delegating their call to
439 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
440 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
441
442 // Permission tokens that have expired, but we remember for error reporting.
443 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
444
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700445 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
446
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447 // Keeps track of the active voice interaction service component, notified from
448 // VoiceInteractionManagerService
449 ComponentName mActiveVoiceInteractionServiceComponent;
450
Michal Karpinskida34cd42019-04-02 19:46:52 +0100451 // A map userId and all its companion app uids
452 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000453
Wale Ogunwalee2172292018-10-25 10:11:10 -0700454 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 KeyguardController mKeyguardController;
456 private final ClientLifecycleManager mLifecycleManager;
457 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700458 /** The controller for all operations related to locktask. */
459 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700460 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700462 boolean mSuppressResizeConfigChanges;
463
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700464 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 new UpdateConfigurationResult();
466
467 static final class UpdateConfigurationResult {
468 // Configuration changes that were updated.
469 int changes;
470 // If the activity was relaunched to match the new configuration.
471 boolean activityRelaunched;
472
473 void reset() {
474 changes = 0;
475 activityRelaunched = false;
476 }
477 }
478
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700479 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 private int mConfigurationSeq;
481 // To cache the list of supported system locales
482 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483
484 /**
485 * Temp object used when global and/or display override configuration is updated. It is also
486 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
487 * anyone...
488 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 private Configuration mTempConfig = new Configuration();
490
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 /** Temporary to avoid allocations. */
492 final StringBuilder mStringBuilder = new StringBuilder(256);
493
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 // Amount of time after a call to stopAppSwitches() during which we will
495 // prevent further untrusted switches from happening.
496 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
497
498 /**
499 * The time at which we will allow normal application switches again,
500 * after a call to {@link #stopAppSwitches()}.
501 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700502 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503 /**
504 * This is set to true after the first switch after mAppSwitchesAllowedTime
505 * is set; any switches after that will clear the time.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508
Ricky Wai906af482019-06-03 17:25:28 +0100509 /**
510 * Last stop app switches time, apps finished before this time cannot start background activity
511 * even if they are in grace period.
512 */
513 private long mLastStopAppSwitchesTime;
514
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 IActivityController mController = null;
516 boolean mControllerIsAMonkey = false;
517
Wale Ogunwale214f3482018-10-04 11:00:47 -0700518 final int mFactoryTest;
519
520 /** Used to control how we initialize the service. */
521 ComponentName mTopComponent;
522 String mTopAction = Intent.ACTION_MAIN;
523 String mTopData;
524
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800525 /** Profiling app information. */
526 String mProfileApp = null;
527 WindowProcessController mProfileProc = null;
528 ProfilerInfo mProfilerInfo = null;
529
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700531 * Dump of the activity state at the time of the last ANR. Cleared after
532 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
533 */
534 String mLastANRState;
535
536 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700537 * Used to retain an update lock when the foreground activity is in
538 * immersive mode.
539 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700540 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541
542 /**
543 * Packages that are being allowed to perform unrestricted app switches. Mapping is
544 * User -> Type -> uid.
545 */
546 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
547
548 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 private int mThumbnailWidth;
550 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700551
552 /**
553 * Flag that indicates if multi-window is enabled.
554 *
555 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
556 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
557 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
558 * At least one of the forms of multi-window must be enabled in order for this flag to be
559 * initialized to 'true'.
560 *
561 * @see #mSupportsSplitScreenMultiWindow
562 * @see #mSupportsFreeformWindowManagement
563 * @see #mSupportsPictureInPicture
564 * @see #mSupportsMultiDisplay
565 */
566 boolean mSupportsMultiWindow;
567 boolean mSupportsSplitScreenMultiWindow;
568 boolean mSupportsFreeformWindowManagement;
569 boolean mSupportsPictureInPicture;
570 boolean mSupportsMultiDisplay;
571 boolean mForceResizableActivities;
572
573 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
574
575 // VR Vr2d Display Id.
576 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700577
Wale Ogunwalef6733932018-06-27 05:14:34 -0700578 /**
579 * Set while we are wanting to sleep, to prevent any
580 * activities from being started/resumed.
581 *
582 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
583 *
584 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
585 * while in the sleep state until there is a pending transition out of sleep, in which case
586 * mSleeping is set to false, and remains false while awake.
587 *
588 * Whether mSleeping can quickly toggled between true/false without the device actually
589 * display changing states is undefined.
590 */
591 private boolean mSleeping = false;
592
593 /**
594 * The process state used for processes that are running the top activities.
595 * This changes between TOP and TOP_SLEEPING to following mSleeping.
596 */
597 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
598
Riddle Hsua0022cd2019-09-09 21:12:41 +0800599 @Retention(RetentionPolicy.SOURCE)
600 @IntDef({
601 LAYOUT_REASON_CONFIG_CHANGED,
602 LAYOUT_REASON_VISIBILITY_CHANGED,
603 })
604 @interface LayoutReason {}
605 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
606 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
607
608 /** The reasons to perform surface placement. */
609 @LayoutReason
610 private int mLayoutReasons;
611
Wale Ogunwalef6733932018-06-27 05:14:34 -0700612 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
613 // automatically. Important for devices without direct input devices.
614 private boolean mShowDialogs = true;
615
616 /** Set if we are shutting down the system, similar to sleeping. */
617 boolean mShuttingDown = false;
618
619 /**
620 * We want to hold a wake lock while running a voice interaction session, since
621 * this may happen with the screen off and we need to keep the CPU running to
622 * be able to continue to interact with the user.
623 */
624 PowerManager.WakeLock mVoiceWakeLock;
625
626 /**
627 * Set while we are running a voice interaction. This overrides sleeping while it is active.
628 */
629 IVoiceInteractionSession mRunningVoice;
630
631 /**
632 * The last resumed activity. This is identical to the current resumed activity most
633 * of the time but could be different when we're pausing one activity before we resume
634 * another activity.
635 */
636 ActivityRecord mLastResumedActivity;
637
638 /**
639 * The activity that is currently being traced as the active resumed activity.
640 *
641 * @see #updateResumedAppTrace
642 */
643 private @Nullable ActivityRecord mTracedResumedActivity;
644
645 /** If non-null, we are tracking the time the user spends in the currently focused app. */
646 AppTimeTracker mCurAppTimeTracker;
647
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700648 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700649
Wale Ogunwale53783742018-09-16 10:21:51 -0700650 /**
651 * Packages that the user has asked to have run in screen size
652 * compatibility mode instead of filling the screen.
653 */
654 CompatModePackages mCompatModePackages;
655
Wale Ogunwalef6733932018-06-27 05:14:34 -0700656 private FontScaleSettingObserver mFontScaleSettingObserver;
657
Ricky Wai96f5c352019-04-10 18:40:17 +0100658 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private final class FontScaleSettingObserver extends ContentObserver {
661 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
662 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
663
664 public FontScaleSettingObserver() {
665 super(mH);
666 final ContentResolver resolver = mContext.getContentResolver();
667 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
668 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
669 UserHandle.USER_ALL);
670 }
671
672 @Override
673 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
674 if (mFontScaleUri.equals(uri)) {
675 updateFontScaleIfNeeded(userId);
676 } else if (mHideErrorDialogsUri.equals(uri)) {
677 synchronized (mGlobalLock) {
678 updateShouldShowDialogsLocked(getGlobalConfiguration());
679 }
680 }
681 }
682 }
683
Riddle Hsua0536432019-02-16 00:38:59 +0800684 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
685 @Target(ElementType.METHOD)
686 @Retention(RetentionPolicy.SOURCE)
687 @interface HotPath {
688 int NONE = 0;
689 int OOM_ADJUSTMENT = 1;
690 int LRU_UPDATE = 2;
691 int PROCESS_CHANGE = 3;
692 int caller() default NONE;
693 }
694
Charles Chen8d98dd22018-12-26 17:36:54 +0800695 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
696 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700697 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700698 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700699 mSystemThread = ActivityThread.currentActivityThread();
700 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700701 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800702 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700703 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700704 }
705
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700706 public void onSystemReady() {
707 synchronized (mGlobalLock) {
708 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
709 PackageManager.FEATURE_CANT_SAVE_STATE);
710 mAssistUtils = new AssistUtils(mContext);
711 mVrController.onSystemReady();
712 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700713 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700714 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void onInitPowerManagement() {
718 synchronized (mGlobalLock) {
719 mStackSupervisor.initPowerManagement();
720 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
721 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
722 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
723 mVoiceWakeLock.setReferenceCounted(false);
724 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700725 }
726
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700728 mFontScaleSettingObserver = new FontScaleSettingObserver();
729 }
730
Wale Ogunwale59507092018-10-29 09:00:30 -0700731 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732 final boolean freeformWindowManagement =
733 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
734 || Settings.Global.getInt(
735 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
736
737 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
738 final boolean supportsPictureInPicture = supportsMultiWindow &&
739 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
740 final boolean supportsSplitScreenMultiWindow =
741 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
742 final boolean supportsMultiDisplay = mContext.getPackageManager()
743 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700744 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
745 final boolean forceResizable = Settings.Global.getInt(
746 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
747
748 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900749 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700750
751 final Configuration configuration = new Configuration();
752 Settings.System.getConfiguration(resolver, configuration);
753 if (forceRtl) {
754 // This will take care of setting the correct layout direction flags
755 configuration.setLayoutDirection(configuration.locale);
756 }
757
758 synchronized (mGlobalLock) {
759 mForceResizableActivities = forceResizable;
760 final boolean multiWindowFormEnabled = freeformWindowManagement
761 || supportsSplitScreenMultiWindow
762 || supportsPictureInPicture
763 || supportsMultiDisplay;
764 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
765 mSupportsMultiWindow = true;
766 mSupportsFreeformWindowManagement = freeformWindowManagement;
767 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
768 mSupportsPictureInPicture = supportsPictureInPicture;
769 mSupportsMultiDisplay = supportsMultiDisplay;
770 } else {
771 mSupportsMultiWindow = false;
772 mSupportsFreeformWindowManagement = false;
773 mSupportsSplitScreenMultiWindow = false;
774 mSupportsPictureInPicture = false;
775 mSupportsMultiDisplay = false;
776 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700777 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 // This happens before any activities are started, so we can change global configuration
779 // in-place.
780 updateConfigurationLocked(configuration, null, true);
781 final Configuration globalConfig = getGlobalConfiguration();
782 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
783
784 // Load resources only after the current configuration has been set.
785 final Resources res = mContext.getResources();
786 mThumbnailWidth = res.getDimensionPixelSize(
787 com.android.internal.R.dimen.thumbnail_width);
788 mThumbnailHeight = res.getDimensionPixelSize(
789 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700790 }
791 }
792
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800793 public WindowManagerGlobalLock getGlobalLock() {
794 return mGlobalLock;
795 }
796
Yunfan Chen585f2932019-01-29 16:04:45 +0900797 /** For test purpose only. */
798 @VisibleForTesting
799 public ActivityTaskManagerInternal getAtmInternal() {
800 return mInternal;
801 }
802
Riddle Hsud93a6c42018-11-29 21:50:06 +0800803 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
804 Looper looper) {
805 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700808 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800809 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700810 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700812
813 mTempConfig.setToDefaults();
814 mTempConfig.setLocales(LocaleList.getDefault());
815 mConfigurationSeq = mTempConfig.seq = 1;
816 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800817 mRootActivityContainer = new RootActivityContainer(this);
818 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700822 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700824 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700826 mKeyguardController = mStackSupervisor.getKeyguardController();
827 }
828
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700829 public void onActivityManagerInternalAdded() {
830 synchronized (mGlobalLock) {
831 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
832 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
833 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700834 }
835
Yunfan Chen75157d72018-07-27 14:47:21 +0900836 int increaseConfigurationSeqLocked() {
837 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
838 return mConfigurationSeq;
839 }
840
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700841 protected ActivityStackSupervisor createStackSupervisor() {
842 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
843 supervisor.initialize();
844 return supervisor;
845 }
846
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800847 protected AppWarnings createAppWarnings(
848 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
849 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setWindowManager(WindowManagerService wm) {
853 synchronized (mGlobalLock) {
854 mWindowManager = wm;
855 mLockTaskController.setWindowManager(wm);
856 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800857 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 }
860
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700861 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
862 synchronized (mGlobalLock) {
863 mUsageStatsInternal = usageStatsManager;
864 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700865 }
866
Wale Ogunwalef6733932018-06-27 05:14:34 -0700867 UserManagerService getUserManager() {
868 if (mUserManager == null) {
869 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
870 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
871 }
872 return mUserManager;
873 }
874
875 AppOpsService getAppOpsService() {
876 if (mAppOpsService == null) {
877 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
878 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
879 }
880 return mAppOpsService;
881 }
882
883 boolean hasUserRestriction(String restriction, int userId) {
884 return getUserManager().hasUserRestriction(restriction, userId);
885 }
886
Michal Karpinski15486842019-04-25 17:33:42 +0100887 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
888 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700889 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100890 if (mode == AppOpsManager.MODE_DEFAULT) {
891 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
892 == PERMISSION_GRANTED;
893 }
894 return mode == AppOpsManager.MODE_ALLOWED;
895 }
896
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700897 @VisibleForTesting
898 protected void setRecentTasks(RecentTasks recentTasks) {
899 mRecentTasks = recentTasks;
900 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700901 }
902
903 RecentTasks getRecentTasks() {
904 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700905 }
906
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700907 ClientLifecycleManager getLifecycleManager() {
908 return mLifecycleManager;
909 }
910
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700911 ActivityStartController getActivityStartController() {
912 return mActivityStartController;
913 }
914
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700915 TaskChangeNotificationController getTaskChangeNotificationController() {
916 return mTaskChangeNotificationController;
917 }
918
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700919 LockTaskController getLockTaskController() {
920 return mLockTaskController;
921 }
922
Yunfan Chen75157d72018-07-27 14:47:21 +0900923 /**
924 * Return the global configuration used by the process corresponding to the input pid. This is
925 * usually the global configuration with some overrides specific to that process.
926 */
927 Configuration getGlobalConfigurationForCallingPid() {
928 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800929 return getGlobalConfigurationForPid(pid);
930 }
931
932 /**
933 * Return the global configuration used by the process corresponding to the given pid.
934 */
935 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900936 if (pid == MY_PID || pid < 0) {
937 return getGlobalConfiguration();
938 }
939 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100940 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900941 return app != null ? app.getConfiguration() : getGlobalConfiguration();
942 }
943 }
944
945 /**
946 * Return the device configuration info used by the process corresponding to the input pid.
947 * The value is consistent with the global configuration for the process.
948 */
949 @Override
950 public ConfigurationInfo getDeviceConfigurationInfo() {
951 ConfigurationInfo config = new ConfigurationInfo();
952 synchronized (mGlobalLock) {
953 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
954 config.reqTouchScreen = globalConfig.touchscreen;
955 config.reqKeyboardType = globalConfig.keyboard;
956 config.reqNavigation = globalConfig.navigation;
957 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
958 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
959 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
960 }
961 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
962 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
963 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
964 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700965 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900966 }
967 return config;
968 }
969
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700970 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700971 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700972 }
973
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700974 public static final class Lifecycle extends SystemService {
975 private final ActivityTaskManagerService mService;
976
977 public Lifecycle(Context context) {
978 super(context);
979 mService = new ActivityTaskManagerService(context);
980 }
981
982 @Override
983 public void onStart() {
984 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700985 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700986 }
987
Garfield Tan891146c2018-10-09 12:14:00 -0700988 @Override
989 public void onUnlockUser(int userId) {
990 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800991 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700992 }
993 }
994
995 @Override
996 public void onCleanupUser(int userId) {
997 synchronized (mService.getGlobalLock()) {
998 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
999 }
1000 }
1001
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 public ActivityTaskManagerService getService() {
1003 return mService;
1004 }
1005 }
1006
1007 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001008 public final int startActivity(IApplicationThread caller, String callingPackage,
1009 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1010 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1011 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1012 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1013 UserHandle.getCallingUserId());
1014 }
1015
1016 @Override
1017 public final int startActivities(IApplicationThread caller, String callingPackage,
1018 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1019 int userId) {
1020 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001021 enforceNotIsolatedCaller(reason);
1022 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001024 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1025 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1026 reason, null /* originatingPendingIntent */,
1027 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 }
1029
1030 @Override
1031 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1032 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1033 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1034 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1035 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1036 true /*validateIncomingUser*/);
1037 }
1038
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001039 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1041 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1042 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001043 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001045 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1047
1048 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001049 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 .setCaller(caller)
1051 .setCallingPackage(callingPackage)
1052 .setResolvedType(resolvedType)
1053 .setResultTo(resultTo)
1054 .setResultWho(resultWho)
1055 .setRequestCode(requestCode)
1056 .setStartFlags(startFlags)
1057 .setProfilerInfo(profilerInfo)
1058 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001059 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 .execute();
1061
1062 }
1063
1064 @Override
1065 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1066 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001067 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1068 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 // Refuse possible leaked file descriptors
1070 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1071 throw new IllegalArgumentException("File descriptors passed in Intent");
1072 }
1073
1074 if (!(target instanceof PendingIntentRecord)) {
1075 throw new IllegalArgumentException("Bad PendingIntent object");
1076 }
1077
1078 PendingIntentRecord pir = (PendingIntentRecord)target;
1079
1080 synchronized (mGlobalLock) {
1081 // If this is coming from the currently resumed activity, it is
1082 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001083 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 if (stack.mResumedActivity != null &&
1085 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001086 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 }
1088 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001089 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 }
1092
1093 @Override
1094 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1095 Bundle bOptions) {
1096 // Refuse possible leaked file descriptors
1097 if (intent != null && intent.hasFileDescriptors()) {
1098 throw new IllegalArgumentException("File descriptors passed in Intent");
1099 }
1100 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1101
1102 synchronized (mGlobalLock) {
1103 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1104 if (r == null) {
1105 SafeActivityOptions.abort(options);
1106 return false;
1107 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001108 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001109 // The caller is not running... d'oh!
1110 SafeActivityOptions.abort(options);
1111 return false;
1112 }
1113 intent = new Intent(intent);
1114 // The caller is not allowed to change the data.
1115 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1116 // And we are resetting to find the next component...
1117 intent.setComponent(null);
1118
1119 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1120
1121 ActivityInfo aInfo = null;
1122 try {
1123 List<ResolveInfo> resolves =
1124 AppGlobals.getPackageManager().queryIntentActivities(
1125 intent, r.resolvedType,
1126 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1127 UserHandle.getCallingUserId()).getList();
1128
1129 // Look for the original activity in the list...
1130 final int N = resolves != null ? resolves.size() : 0;
1131 for (int i=0; i<N; i++) {
1132 ResolveInfo rInfo = resolves.get(i);
1133 if (rInfo.activityInfo.packageName.equals(r.packageName)
1134 && rInfo.activityInfo.name.equals(r.info.name)) {
1135 // We found the current one... the next matching is
1136 // after it.
1137 i++;
1138 if (i<N) {
1139 aInfo = resolves.get(i).activityInfo;
1140 }
1141 if (debug) {
1142 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1143 + "/" + r.info.name);
1144 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1145 ? "null" : aInfo.packageName + "/" + aInfo.name));
1146 }
1147 break;
1148 }
1149 }
1150 } catch (RemoteException e) {
1151 }
1152
1153 if (aInfo == null) {
1154 // Nobody who is next!
1155 SafeActivityOptions.abort(options);
1156 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1157 return false;
1158 }
1159
1160 intent.setComponent(new ComponentName(
1161 aInfo.applicationInfo.packageName, aInfo.name));
1162 intent.setFlags(intent.getFlags()&~(
1163 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1164 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1165 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1166 FLAG_ACTIVITY_NEW_TASK));
1167
1168 // Okay now we need to start the new activity, replacing the currently running activity.
1169 // This is a little tricky because we want to start the new one as if the current one is
1170 // finished, but not finish the current one first so that there is no flicker.
1171 // And thus...
1172 final boolean wasFinishing = r.finishing;
1173 r.finishing = true;
1174
1175 // Propagate reply information over to the new activity.
1176 final ActivityRecord resultTo = r.resultTo;
1177 final String resultWho = r.resultWho;
1178 final int requestCode = r.requestCode;
1179 r.resultTo = null;
1180 if (resultTo != null) {
1181 resultTo.removeResultsLocked(r, resultWho, requestCode);
1182 }
1183
1184 final long origId = Binder.clearCallingIdentity();
1185 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001186 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001187 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001188 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001189 .setResolvedType(r.resolvedType)
1190 .setActivityInfo(aInfo)
1191 .setResultTo(resultTo != null ? resultTo.appToken : null)
1192 .setResultWho(resultWho)
1193 .setRequestCode(requestCode)
1194 .setCallingPid(-1)
1195 .setCallingUid(r.launchedFromUid)
1196 .setCallingPackage(r.launchedFromPackage)
1197 .setRealCallingPid(-1)
1198 .setRealCallingUid(r.launchedFromUid)
1199 .setActivityOptions(options)
1200 .execute();
1201 Binder.restoreCallingIdentity(origId);
1202
1203 r.finishing = wasFinishing;
1204 if (res != ActivityManager.START_SUCCESS) {
1205 return false;
1206 }
1207 return true;
1208 }
1209 }
1210
1211 @Override
1212 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1213 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1214 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1215 final WaitResult res = new WaitResult();
1216 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001217 enforceNotIsolatedCaller("startActivityAndWait");
1218 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1219 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001221 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 .setCaller(caller)
1223 .setCallingPackage(callingPackage)
1224 .setResolvedType(resolvedType)
1225 .setResultTo(resultTo)
1226 .setResultWho(resultWho)
1227 .setRequestCode(requestCode)
1228 .setStartFlags(startFlags)
1229 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001230 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001231 .setProfilerInfo(profilerInfo)
1232 .setWaitResult(res)
1233 .execute();
1234 }
1235 return res;
1236 }
1237
1238 @Override
1239 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1240 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1241 int startFlags, Configuration config, Bundle bOptions, int userId) {
1242 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001243 enforceNotIsolatedCaller("startActivityWithConfig");
1244 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1245 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001247 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001248 .setCaller(caller)
1249 .setCallingPackage(callingPackage)
1250 .setResolvedType(resolvedType)
1251 .setResultTo(resultTo)
1252 .setResultWho(resultWho)
1253 .setRequestCode(requestCode)
1254 .setStartFlags(startFlags)
1255 .setGlobalConfiguration(config)
1256 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001257 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001258 .execute();
1259 }
1260 }
1261
Alison Cichowlas3e340502018-08-07 17:15:01 -04001262
1263 @Override
1264 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1265 int callingUid = Binder.getCallingUid();
1266 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1267 throw new SecurityException("Only the system process can request a permission token, "
1268 + "received request from uid: " + callingUid);
1269 }
1270 IBinder permissionToken = new Binder();
1271 synchronized (mGlobalLock) {
1272 mStartActivitySources.put(permissionToken, delegatorToken);
1273 }
1274
1275 Message expireMsg = PooledLambda.obtainMessage(
1276 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1277 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1278
1279 Message forgetMsg = PooledLambda.obtainMessage(
1280 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1281 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1282
1283 return permissionToken;
1284 }
1285
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 @Override
1287 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1288 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001289 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1290 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001292 // permission grants) as any app that may launch one of your own activities. So we only
1293 // allow this in two cases:
1294 // 1) The caller is an activity that is part of the core framework, and then only when it
1295 // is running as the system.
1296 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1297 // can only be requested by a system activity, which may then delegate this call to
1298 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 final ActivityRecord sourceRecord;
1300 final int targetUid;
1301 final String targetPackage;
1302 final boolean isResolver;
1303 synchronized (mGlobalLock) {
1304 if (resultTo == null) {
1305 throw new SecurityException("Must be called from an activity");
1306 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 final IBinder sourceToken;
1308 if (permissionToken != null) {
1309 // To even attempt to use a permissionToken, an app must also have this signature
1310 // permission.
1311 mAmInternal.enforceCallingPermission(
1312 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1313 "startActivityAsCaller");
1314 // If called with a permissionToken, we want the sourceRecord from the delegator
1315 // activity that requested this token.
1316 sourceToken = mStartActivitySources.remove(permissionToken);
1317 if (sourceToken == null) {
1318 // Invalid permissionToken, check if it recently expired.
1319 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1320 throw new SecurityException("Called with expired permission token: "
1321 + permissionToken);
1322 } else {
1323 throw new SecurityException("Called with invalid permission token: "
1324 + permissionToken);
1325 }
1326 }
1327 } else {
1328 // This method was called directly by the source.
1329 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331
Wale Ogunwaled32da472018-11-16 07:19:28 -08001332 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333 if (sourceRecord == null) {
1334 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 }
1336 if (sourceRecord.app == null) {
1337 throw new SecurityException("Called without a process attached to activity");
1338 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339
1340 // Whether called directly or from a delegate, the source activity must be from the
1341 // android package.
1342 if (!sourceRecord.info.packageName.equals("android")) {
1343 throw new SecurityException("Must be called from an activity that is "
1344 + "declared in the android package");
1345 }
1346
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001347 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 // This is still okay, as long as this activity is running under the
1349 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001350 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001352 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 + " must be system uid or original calling uid "
1354 + sourceRecord.launchedFromUid);
1355 }
1356 }
1357 if (ignoreTargetSecurity) {
1358 if (intent.getComponent() == null) {
1359 throw new SecurityException(
1360 "Component must be specified with ignoreTargetSecurity");
1361 }
1362 if (intent.getSelector() != null) {
1363 throw new SecurityException(
1364 "Selector not allowed with ignoreTargetSecurity");
1365 }
1366 }
1367 targetUid = sourceRecord.launchedFromUid;
1368 targetPackage = sourceRecord.launchedFromPackage;
1369 isResolver = sourceRecord.isResolverOrChildActivity();
1370 }
1371
1372 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001373 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 }
1375
1376 // TODO: Switch to user app stacks here.
1377 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(targetUid)
1380 .setCallingPackage(targetPackage)
1381 .setResolvedType(resolvedType)
1382 .setResultTo(resultTo)
1383 .setResultWho(resultWho)
1384 .setRequestCode(requestCode)
1385 .setStartFlags(startFlags)
1386 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001387 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1389 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001390 // The target may well be in the background, which would normally prevent it
1391 // from starting an activity. Here we definitely want the start to succeed.
1392 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001393 .execute();
1394 } catch (SecurityException e) {
1395 // XXX need to figure out how to propagate to original app.
1396 // A SecurityException here is generally actually a fault of the original
1397 // calling activity (such as a fairly granting permissions), so propagate it
1398 // back to them.
1399 /*
1400 StringBuilder msg = new StringBuilder();
1401 msg.append("While launching");
1402 msg.append(intent.toString());
1403 msg.append(": ");
1404 msg.append(e.getMessage());
1405 */
1406 throw e;
1407 }
1408 }
1409
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1411 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1412 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1413 }
1414
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 @Override
1416 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1417 Intent intent, String resolvedType, IVoiceInteractionSession session,
1418 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1419 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001420 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 if (session == null || interactor == null) {
1422 throw new NullPointerException("null session or interactor");
1423 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001424 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001426 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 .setCallingUid(callingUid)
1428 .setCallingPackage(callingPackage)
1429 .setResolvedType(resolvedType)
1430 .setVoiceSession(session)
1431 .setVoiceInteractor(interactor)
1432 .setStartFlags(startFlags)
1433 .setProfilerInfo(profilerInfo)
1434 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001435 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001436 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .execute();
1438 }
1439
1440 @Override
1441 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1442 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1444 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001446 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .setCallingUid(callingUid)
1448 .setCallingPackage(callingPackage)
1449 .setResolvedType(resolvedType)
1450 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001451 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001452 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 .execute();
1454 }
1455
Riddle Hsu609a8e22019-06-27 16:46:29 -06001456 /**
1457 * Start the recents activity to perform the recents animation.
1458 *
1459 * @param intent The intent to start the recents activity.
1460 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1461 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001463 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1464 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001467 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 final long origId = Binder.clearCallingIdentity();
1469 try {
1470 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001471 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1472 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001473 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474
1475 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001476 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001477 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001478 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001479 if (recentsAnimationRunner == null) {
1480 anim.preloadRecentsActivity();
1481 } else {
1482 anim.startRecentsActivity(recentsAnimationRunner);
1483 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(origId);
1487 }
1488 }
1489
1490 @Override
1491 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001492 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 "startActivityFromRecents()");
1494
1495 final int callingPid = Binder.getCallingPid();
1496 final int callingUid = Binder.getCallingUid();
1497 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1498 final long origId = Binder.clearCallingIdentity();
1499 try {
1500 synchronized (mGlobalLock) {
1501 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1502 safeOptions);
1503 }
1504 } finally {
1505 Binder.restoreCallingIdentity(origId);
1506 }
1507 }
1508
1509 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001510 * Public API to check if the client is allowed to start an activity on specified display.
1511 *
1512 * If the target display is private or virtual, some restrictions will apply.
1513 *
1514 * @param displayId Target display id.
1515 * @param intent Intent used to launch the activity.
1516 * @param resolvedType The MIME type of the intent.
1517 * @param userId The id of the user for whom the call is made.
1518 * @return {@code true} if a call to start an activity on the target display should succeed and
1519 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1520 */
1521 @Override
1522 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1523 String resolvedType, int userId) {
1524 final int callingUid = Binder.getCallingUid();
1525 final int callingPid = Binder.getCallingPid();
1526 final long origId = Binder.clearCallingIdentity();
1527
1528 try {
1529 // Collect information about the target of the Intent.
1530 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1531 0 /* startFlags */, null /* profilerInfo */, userId,
1532 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1533 UserHandle.USER_NULL));
1534 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1535
1536 synchronized (mGlobalLock) {
1537 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1538 aInfo);
1539 }
1540 } finally {
1541 Binder.restoreCallingIdentity(origId);
1542 }
1543 }
1544
1545 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 * This is the internal entry point for handling Activity.finish().
1547 *
1548 * @param token The Binder token referencing the Activity we want to finish.
1549 * @param resultCode Result code, if any, from this Activity.
1550 * @param resultData Result data (Intent), if any, from this Activity.
1551 * @param finishTask Whether to finish the task associated with this Activity.
1552 *
1553 * @return Returns true if the activity successfully finished, or false if it is still running.
1554 */
1555 @Override
1556 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1557 int finishTask) {
1558 // Refuse possible leaked file descriptors
1559 if (resultData != null && resultData.hasFileDescriptors()) {
1560 throw new IllegalArgumentException("File descriptors passed in Intent");
1561 }
1562
1563 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001564 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 if (r == null) {
1566 return true;
1567 }
1568 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001569 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001570 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (rootR == null) {
1572 Slog.w(TAG, "Finishing task with all activities already finished");
1573 }
1574 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1575 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001576 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 return false;
1578 }
1579
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1581 // We should consolidate.
1582 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001584 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 if (next != null) {
1586 // ask watcher if this is allowed
1587 boolean resumeOK = true;
1588 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001589 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001591 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 Watchdog.getInstance().setActivityController(null);
1593 }
1594
1595 if (!resumeOK) {
1596 Slog.i(TAG, "Not finishing activity because controller resumed");
1597 return false;
1598 }
1599 }
1600 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001601
1602 // note down that the process has finished an activity and is in background activity
1603 // starts grace period
1604 if (r.app != null) {
1605 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1606 }
1607
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001608 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001609 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 try {
1611 boolean res;
1612 final boolean finishWithRootActivity =
1613 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1614 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1615 || (finishWithRootActivity && r == rootR)) {
1616 // If requested, remove the task that is associated to this activity only if it
1617 // was the root activity in the task. The result code and data is ignored
1618 // because we don't support returning them across task boundaries. Also, to
1619 // keep backwards compatibility we remove the task from recents when finishing
1620 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001621 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 finishWithRootActivity, "finish-activity");
1623 if (!res) {
1624 Slog.i(TAG, "Removing task failed to finish activity");
1625 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001626 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001627 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001629 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001630 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001631 if (!res) {
1632 Slog.i(TAG, "Failed to finish by app-request");
1633 }
1634 }
1635 return res;
1636 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001637 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 Binder.restoreCallingIdentity(origId);
1639 }
1640 }
1641 }
1642
1643 @Override
1644 public boolean finishActivityAffinity(IBinder token) {
1645 synchronized (mGlobalLock) {
1646 final long origId = Binder.clearCallingIdentity();
1647 try {
1648 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1649 if (r == null) {
1650 return false;
1651 }
1652
1653 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1654 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001655 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001656 return false;
1657 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001658 r.finishActivityAffinity();
1659 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 } finally {
1661 Binder.restoreCallingIdentity(origId);
1662 }
1663 }
1664 }
1665
1666 @Override
1667 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1668 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001669 try {
1670 WindowProcessController proc = null;
1671 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001672 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001673 ActivityStack stack = ActivityRecord.getStackLocked(token);
1674 if (stack == null) {
1675 return;
1676 }
1677 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1678 false /* fromTimeout */, false /* processPausingActivities */, config);
1679 if (r != null) {
1680 proc = r.app;
1681 }
1682 if (stopProfiling && proc != null) {
1683 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001686 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001687 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001688 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 }
1691
1692 @Override
1693 public final void activityResumed(IBinder token) {
1694 final long origId = Binder.clearCallingIdentity();
1695 synchronized (mGlobalLock) {
1696 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 }
1698 Binder.restoreCallingIdentity(origId);
1699 }
1700
1701 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001702 public final void activityTopResumedStateLost() {
1703 final long origId = Binder.clearCallingIdentity();
1704 synchronized (mGlobalLock) {
1705 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1706 }
1707 Binder.restoreCallingIdentity(origId);
1708 }
1709
1710 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 public final void activityPaused(IBinder token) {
1712 final long origId = Binder.clearCallingIdentity();
1713 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001714 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 ActivityStack stack = ActivityRecord.getStackLocked(token);
1716 if (stack != null) {
1717 stack.activityPausedLocked(token, false);
1718 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001719 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 }
1721 Binder.restoreCallingIdentity(origId);
1722 }
1723
1724 @Override
1725 public final void activityStopped(IBinder token, Bundle icicle,
1726 PersistableBundle persistentState, CharSequence description) {
1727 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1728
1729 // Refuse possible leaked file descriptors
1730 if (icicle != null && icicle.hasFileDescriptors()) {
1731 throw new IllegalArgumentException("File descriptors passed in Bundle");
1732 }
1733
1734 final long origId = Binder.clearCallingIdentity();
1735
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001736 String restartingName = null;
1737 int restartingUid = 0;
1738 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001740 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001741 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 if (r.attachedToProcess()
1744 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1745 // The activity was requested to restart from
1746 // {@link #restartActivityProcessIfVisible}.
1747 restartingName = r.app.mName;
1748 restartingUid = r.app.mUid;
1749 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001750 r.activityStoppedLocked(icicle, persistentState, description);
1751 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001752 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 }
1754
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001755 if (restartingName != null) {
1756 // In order to let the foreground activity can be restarted with its saved state from
1757 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1758 // until the activity reports stopped with the state. And the activity record will be
1759 // kept because the record state is restarting, then the activity will be restarted
1760 // immediately if it is still the top one.
1761 mStackSupervisor.removeRestartTimeouts(r);
1762 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1763 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001764 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001765
1766 Binder.restoreCallingIdentity(origId);
1767 }
1768
1769 @Override
1770 public final void activityDestroyed(IBinder token) {
1771 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1772 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001773 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001775 try {
1776 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1777 if (activity != null) {
1778 activity.destroyed("activityDestroyed");
1779 }
1780 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001781 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001782 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783 }
1784 }
1785 }
1786
1787 @Override
1788 public final void activityRelaunched(IBinder token) {
1789 final long origId = Binder.clearCallingIdentity();
1790 synchronized (mGlobalLock) {
1791 mStackSupervisor.activityRelaunchedLocked(token);
1792 }
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795
1796 public final void activitySlept(IBinder token) {
1797 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1798
1799 final long origId = Binder.clearCallingIdentity();
1800
1801 synchronized (mGlobalLock) {
1802 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1803 if (r != null) {
1804 mStackSupervisor.activitySleptLocked(r);
1805 }
1806 }
1807
1808 Binder.restoreCallingIdentity(origId);
1809 }
1810
1811 @Override
1812 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1813 synchronized (mGlobalLock) {
1814 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1815 if (r == null) {
1816 return;
1817 }
1818 final long origId = Binder.clearCallingIdentity();
1819 try {
1820 r.setRequestedOrientation(requestedOrientation);
1821 } finally {
1822 Binder.restoreCallingIdentity(origId);
1823 }
1824 }
1825 }
1826
1827 @Override
1828 public int getRequestedOrientation(IBinder token) {
1829 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001830 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1831 return (r != null)
1832 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 }
1834 }
1835
1836 @Override
1837 public void setImmersive(IBinder token, boolean immersive) {
1838 synchronized (mGlobalLock) {
1839 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1840 if (r == null) {
1841 throw new IllegalArgumentException();
1842 }
1843 r.immersive = immersive;
1844
1845 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001846 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001848 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
1850 }
1851 }
1852
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001853 void applyUpdateLockStateLocked(ActivityRecord r) {
1854 // Modifications to the UpdateLock state are done on our handler, outside
1855 // the activity manager's locks. The new state is determined based on the
1856 // state *now* of the relevant activity record. The object is passed to
1857 // the handler solely for logging detail, not to be consulted/modified.
1858 final boolean nextState = r != null && r.immersive;
1859 mH.post(() -> {
1860 if (mUpdateLock.isHeld() != nextState) {
1861 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1862 "Applying new update lock state '" + nextState + "' for " + r);
1863 if (nextState) {
1864 mUpdateLock.acquire();
1865 } else {
1866 mUpdateLock.release();
1867 }
1868 }
1869 });
1870 }
1871
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 @Override
1873 public boolean isImmersive(IBinder token) {
1874 synchronized (mGlobalLock) {
1875 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1876 if (r == null) {
1877 throw new IllegalArgumentException();
1878 }
1879 return r.immersive;
1880 }
1881 }
1882
1883 @Override
1884 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001887 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001888 return (r != null) ? r.immersive : false;
1889 }
1890 }
1891
1892 @Override
1893 public void overridePendingTransition(IBinder token, String packageName,
1894 int enterAnim, int exitAnim) {
1895 synchronized (mGlobalLock) {
1896 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1897 if (self == null) {
1898 return;
1899 }
1900
1901 final long origId = Binder.clearCallingIdentity();
1902
1903 if (self.isState(
1904 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001905 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001906 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 }
1908
1909 Binder.restoreCallingIdentity(origId);
1910 }
1911 }
1912
1913 @Override
1914 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001917 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001918 if (r == null) {
1919 return ActivityManager.COMPAT_MODE_UNKNOWN;
1920 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001921 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 }
1923 }
1924
1925 @Override
1926 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001927 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001929 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001930 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001931 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 if (r == null) {
1933 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1934 return;
1935 }
1936 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001937 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 }
1939 }
1940
1941 @Override
1942 public int getLaunchedFromUid(IBinder activityToken) {
1943 ActivityRecord srec;
1944 synchronized (mGlobalLock) {
1945 srec = ActivityRecord.forTokenLocked(activityToken);
1946 }
1947 if (srec == null) {
1948 return -1;
1949 }
1950 return srec.launchedFromUid;
1951 }
1952
1953 @Override
1954 public String getLaunchedFromPackage(IBinder activityToken) {
1955 ActivityRecord srec;
1956 synchronized (mGlobalLock) {
1957 srec = ActivityRecord.forTokenLocked(activityToken);
1958 }
1959 if (srec == null) {
1960 return null;
1961 }
1962 return srec.launchedFromPackage;
1963 }
1964
1965 @Override
1966 public boolean convertFromTranslucent(IBinder token) {
1967 final long origId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
1970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 return false;
1973 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001974 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 }
1976 } finally {
1977 Binder.restoreCallingIdentity(origId);
1978 }
1979 }
1980
1981 @Override
1982 public boolean convertToTranslucent(IBinder token, Bundle options) {
1983 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1984 final long origId = Binder.clearCallingIdentity();
1985 try {
1986 synchronized (mGlobalLock) {
1987 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1988 if (r == null) {
1989 return false;
1990 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001991 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 int index = task.mActivities.lastIndexOf(r);
1993 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001994 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1996 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001997 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001998 }
1999 } finally {
2000 Binder.restoreCallingIdentity(origId);
2001 }
2002 }
2003
2004 @Override
2005 public void notifyActivityDrawn(IBinder token) {
2006 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2007 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002008 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002010 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 }
2012 }
2013 }
2014
2015 @Override
2016 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2017 synchronized (mGlobalLock) {
2018 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2019 if (r == null) {
2020 return;
2021 }
2022 r.reportFullyDrawnLocked(restoredFromBundle);
2023 }
2024 }
2025
2026 @Override
2027 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2028 synchronized (mGlobalLock) {
2029 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2030 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2031 return stack.mDisplayId;
2032 }
2033 return DEFAULT_DISPLAY;
2034 }
2035 }
2036
2037 @Override
2038 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002039 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 long ident = Binder.clearCallingIdentity();
2041 try {
2042 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002043 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002045 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 }
2047 return null;
2048 }
2049 } finally {
2050 Binder.restoreCallingIdentity(ident);
2051 }
2052 }
2053
2054 @Override
2055 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002056 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2058 final long callingId = Binder.clearCallingIdentity();
2059 try {
2060 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002061 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (stack == null) {
2063 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2064 return;
2065 }
2066 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002067 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 }
2070 }
2071 } finally {
2072 Binder.restoreCallingIdentity(callingId);
2073 }
2074 }
2075
2076 @Override
2077 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002078 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2080 final long callingId = Binder.clearCallingIdentity();
2081 try {
2082 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002083 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002084 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (task == null) {
2086 return;
2087 }
2088 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002089 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002090 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 }
2092 }
2093 } finally {
2094 Binder.restoreCallingIdentity(callingId);
2095 }
2096 }
2097
2098 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002099 public void restartActivityProcessIfVisible(IBinder activityToken) {
2100 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2101 final long callingId = Binder.clearCallingIdentity();
2102 try {
2103 synchronized (mGlobalLock) {
2104 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2105 if (r == null) {
2106 return;
2107 }
2108 r.restartProcessIfVisible();
2109 }
2110 } finally {
2111 Binder.restoreCallingIdentity(callingId);
2112 }
2113 }
2114
2115 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002117 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 synchronized (mGlobalLock) {
2119 final long ident = Binder.clearCallingIdentity();
2120 try {
2121 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2122 "remove-task");
2123 } finally {
2124 Binder.restoreCallingIdentity(ident);
2125 }
2126 }
2127 }
2128
2129 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002130 public void removeAllVisibleRecentTasks() {
2131 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2132 synchronized (mGlobalLock) {
2133 final long ident = Binder.clearCallingIdentity();
2134 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002135 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002136 } finally {
2137 Binder.restoreCallingIdentity(ident);
2138 }
2139 }
2140 }
2141
2142 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002143 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2144 synchronized (mGlobalLock) {
2145 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2146 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002147 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002148 }
2149 }
2150 return false;
2151 }
2152
2153 @Override
2154 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2155 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002156
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002157 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002158 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2159 if (r != null) {
2160 return r.getActivityStack().navigateUpToLocked(
2161 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002162 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002163 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 }
2165 }
2166
2167 /**
2168 * Attempts to move a task backwards in z-order (the order of activities within the task is
2169 * unchanged).
2170 *
2171 * There are several possible results of this call:
2172 * - if the task is locked, then we will show the lock toast
2173 * - if there is a task behind the provided task, then that task is made visible and resumed as
2174 * this task is moved to the back
2175 * - otherwise, if there are no other tasks in the stack:
2176 * - if this task is in the pinned stack, then we remove the stack completely, which will
2177 * have the effect of moving the task to the top or bottom of the fullscreen stack
2178 * (depending on whether it is visible)
2179 * - otherwise, we simply return home and hide this task
2180 *
2181 * @param token A reference to the activity we wish to move
2182 * @param nonRoot If false then this only works if the activity is the root
2183 * of a task; if true it will work for any activity in a task.
2184 * @return Returns true if the move completed, false if not.
2185 */
2186 @Override
2187 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002188 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 synchronized (mGlobalLock) {
2190 final long origId = Binder.clearCallingIdentity();
2191 try {
2192 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002193 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194 if (task != null) {
2195 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2196 }
2197 } finally {
2198 Binder.restoreCallingIdentity(origId);
2199 }
2200 }
2201 return false;
2202 }
2203
2204 @Override
2205 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002206 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207 long ident = Binder.clearCallingIdentity();
2208 Rect rect = new Rect();
2209 try {
2210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002211 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2213 if (task == null) {
2214 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2215 return rect;
2216 }
2217 if (task.getStack() != null) {
2218 // Return the bounds from window manager since it will be adjusted for various
2219 // things like the presense of a docked stack for tasks that aren't resizeable.
2220 task.getWindowContainerBounds(rect);
2221 } else {
2222 // Task isn't in window manager yet since it isn't associated with a stack.
2223 // Return the persist value from activity manager
2224 if (!task.matchParentBounds()) {
2225 rect.set(task.getBounds());
2226 } else if (task.mLastNonFullscreenBounds != null) {
2227 rect.set(task.mLastNonFullscreenBounds);
2228 }
2229 }
2230 }
2231 } finally {
2232 Binder.restoreCallingIdentity(ident);
2233 }
2234 return rect;
2235 }
2236
2237 @Override
2238 public ActivityManager.TaskDescription getTaskDescription(int id) {
2239 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002240 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002242 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2244 if (tr != null) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002245 return tr.mTaskDescription;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 }
2247 }
2248 return null;
2249 }
2250
2251 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002252 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2253 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2254 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2255 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2256 return;
2257 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002258 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002259 synchronized (mGlobalLock) {
2260 final long ident = Binder.clearCallingIdentity();
2261 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002262 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002263 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002264 if (task == null) {
2265 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2266 return;
2267 }
2268
2269 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2270 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2271
2272 if (!task.isActivityTypeStandardOrUndefined()) {
2273 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2274 + " non-standard task " + taskId + " to windowing mode="
2275 + windowingMode);
2276 }
2277
2278 final ActivityStack stack = task.getStack();
2279 if (toTop) {
2280 stack.moveToFront("setTaskWindowingMode", task);
2281 }
2282 stack.setWindowingMode(windowingMode);
2283 } finally {
2284 Binder.restoreCallingIdentity(ident);
2285 }
2286 }
2287 }
2288
2289 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002291 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002292 ActivityRecord r = getCallingRecordLocked(token);
2293 return r != null ? r.info.packageName : null;
2294 }
2295 }
2296
2297 @Override
2298 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002299 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 ActivityRecord r = getCallingRecordLocked(token);
2301 return r != null ? r.intent.getComponent() : null;
2302 }
2303 }
2304
2305 private ActivityRecord getCallingRecordLocked(IBinder token) {
2306 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2307 if (r == null) {
2308 return null;
2309 }
2310 return r.resultTo;
2311 }
2312
2313 @Override
2314 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002315 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002316
2317 synchronized (mGlobalLock) {
2318 final long origId = Binder.clearCallingIdentity();
2319 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002320 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002321 } finally {
2322 Binder.restoreCallingIdentity(origId);
2323 }
2324 }
2325 }
2326
Mark Renouf446251d2019-04-26 10:22:41 -04002327 @Override
2328 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2329 synchronized (mGlobalLock) {
2330 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2331 if (r == null) {
2332 return;
2333 }
2334 ActivityStack stack = r.getActivityStack();
2335 if (stack != null && stack.isSingleTaskInstance()) {
2336 // Single-task stacks are used for activities which are presented in floating
2337 // windows above full screen activities. Instead of directly finishing the
2338 // task, a task change listener is used to notify SystemUI so the action can be
2339 // handled specially.
2340 final TaskRecord task = r.getTaskRecord();
2341 mTaskChangeNotificationController
2342 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2343 } else {
2344 try {
2345 callback.requestFinish();
2346 } catch (RemoteException e) {
2347 Slog.e(TAG, "Failed to invoke request finish callback", e);
2348 }
2349 }
2350 }
2351 }
2352
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002353 /**
2354 * TODO: Add mController hook
2355 */
2356 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2358 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002359 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360
2361 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2362 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2364 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002365 }
2366 }
2367
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2369 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002370 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002371
Ricky Waiaca8a772019-04-04 16:01:06 +01002372 final int callingPid = Binder.getCallingPid();
2373 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002374 if (!isSameApp(callingUid, callingPackage)) {
2375 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2376 + Binder.getCallingPid() + " as package " + callingPackage;
2377 Slog.w(TAG, msg);
2378 throw new SecurityException(msg);
2379 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002381 SafeActivityOptions.abort(options);
2382 return;
2383 }
2384 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002385 WindowProcessController callerApp = null;
2386 if (appThread != null) {
2387 callerApp = getProcessController(appThread);
2388 }
2389 final ActivityStarter starter = getActivityStartController().obtainStarter(
2390 null /* intent */, "moveTaskToFront");
2391 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2392 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002393 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002394 return;
2395 }
2396 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002398 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 if (task == null) {
2400 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002401 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 return;
2403 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002404 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002406 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 return;
2408 }
2409 ActivityOptions realOptions = options != null
2410 ? options.getOptions(mStackSupervisor)
2411 : null;
2412 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2413 false /* forceNonResizable */);
2414
2415 final ActivityRecord topActivity = task.getTopActivity();
2416 if (topActivity != null) {
2417
2418 // We are reshowing a task, use a starting window to hide the initial draw delay
2419 // so the transition can start earlier.
2420 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2421 true /* taskSwitch */, fromRecents);
2422 }
2423 } finally {
2424 Binder.restoreCallingIdentity(origId);
2425 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002426 }
2427
Ricky Waiaca8a772019-04-04 16:01:06 +01002428 /**
2429 * Return true if callingUid is system, or packageName belongs to that callingUid.
2430 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002431 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002432 try {
2433 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2434 if (packageName == null) {
2435 return false;
2436 }
2437 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2438 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2439 UserHandle.getUserId(callingUid));
2440 return UserHandle.isSameApp(callingUid, uid);
2441 }
2442 } catch (RemoteException e) {
2443 // Should not happen
2444 }
2445 return true;
2446 }
2447
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2449 int callingPid, int callingUid, String name) {
2450 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2451 return true;
2452 }
2453
2454 if (getRecentTasks().isCallerRecents(sourceUid)) {
2455 return true;
2456 }
2457
2458 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2459 if (perm == PackageManager.PERMISSION_GRANTED) {
2460 return true;
2461 }
2462 if (checkAllowAppSwitchUid(sourceUid)) {
2463 return true;
2464 }
2465
2466 // If the actual IPC caller is different from the logical source, then
2467 // also see if they are allowed to control app switches.
2468 if (callingUid != -1 && callingUid != sourceUid) {
2469 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2470 if (perm == PackageManager.PERMISSION_GRANTED) {
2471 return true;
2472 }
2473 if (checkAllowAppSwitchUid(callingUid)) {
2474 return true;
2475 }
2476 }
2477
2478 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2479 return false;
2480 }
2481
2482 private boolean checkAllowAppSwitchUid(int uid) {
2483 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2484 if (types != null) {
2485 for (int i = types.size() - 1; i >= 0; i--) {
2486 if (types.valueAt(i).intValue() == uid) {
2487 return true;
2488 }
2489 }
2490 }
2491 return false;
2492 }
2493
2494 @Override
2495 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2496 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2497 "setActivityController()");
2498 synchronized (mGlobalLock) {
2499 mController = controller;
2500 mControllerIsAMonkey = imAMonkey;
2501 Watchdog.getInstance().setActivityController(controller);
2502 }
2503 }
2504
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002505 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002506 synchronized (mGlobalLock) {
2507 return mController != null && mControllerIsAMonkey;
2508 }
2509 }
2510
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002511 @Override
2512 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2513 synchronized (mGlobalLock) {
2514 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2515 }
2516 }
2517
2518 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2520 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2521 }
2522
2523 @Override
2524 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2525 @WindowConfiguration.ActivityType int ignoreActivityType,
2526 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2527 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002528 final int callingPid = Binder.getCallingPid();
2529 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002530 final int[] profileIds = getUserManager().getProfileIds(
2531 UserHandle.getUserId(callingUid), true);
2532 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2533 for (int i = 0; i < profileIds.length; i++) {
2534 callingProfileIds.add(profileIds[i]);
2535 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002536 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2537
2538 synchronized (mGlobalLock) {
2539 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2540
Nicholas Sauer0259e532019-08-30 08:24:55 -07002541 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002542 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002543 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 }
2545
2546 return list;
2547 }
2548
2549 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2551 synchronized (mGlobalLock) {
2552 final long origId = Binder.clearCallingIdentity();
2553 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2554 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002555 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002556 }
2557 Binder.restoreCallingIdentity(origId);
2558 }
2559 }
2560
2561 @Override
2562 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002563 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002564 ActivityStack stack = ActivityRecord.getStackLocked(token);
2565 if (stack != null) {
2566 return stack.willActivityBeVisibleLocked(token);
2567 }
2568 return false;
2569 }
2570 }
2571
2572 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002575 synchronized (mGlobalLock) {
2576 final long ident = Binder.clearCallingIdentity();
2577 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002578 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002579 if (task == null) {
2580 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2581 return;
2582 }
2583
2584 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2585 + " to stackId=" + stackId + " toTop=" + toTop);
2586
Wale Ogunwaled32da472018-11-16 07:19:28 -08002587 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588 if (stack == null) {
2589 throw new IllegalStateException(
2590 "moveTaskToStack: No stack for stackId=" + stackId);
2591 }
2592 if (!stack.isActivityTypeStandardOrUndefined()) {
2593 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2594 + taskId + " to stack " + stackId);
2595 }
2596 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002597 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2599 }
2600 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2601 "moveTaskToStack");
2602 } finally {
2603 Binder.restoreCallingIdentity(ident);
2604 }
2605 }
2606 }
2607
2608 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002609 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2610 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611
2612 final long ident = Binder.clearCallingIdentity();
2613 try {
2614 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002615 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2616 if (stack == null) {
2617 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2618 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002620 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2621 throw new IllegalArgumentException("Stack: " + stackId
2622 + " doesn't support animated resize.");
2623 }
2624 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2625 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626 }
2627 } finally {
2628 Binder.restoreCallingIdentity(ident);
2629 }
2630 }
2631
wilsonshih5c4cf522019-01-25 09:03:47 +08002632 @Override
2633 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2634 int animationDuration) {
2635 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2636
2637 final long ident = Binder.clearCallingIdentity();
2638 try {
2639 synchronized (mGlobalLock) {
2640 if (xOffset == 0 && yOffset == 0) {
2641 return;
2642 }
2643 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2644 if (stack == null) {
2645 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2646 return;
2647 }
2648 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2649 throw new IllegalArgumentException("Stack: " + stackId
2650 + " doesn't support animated resize.");
2651 }
2652 final Rect destBounds = new Rect();
2653 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002654 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002655 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2656 return;
2657 }
2658 destBounds.offset(xOffset, yOffset);
2659 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2660 animationDuration, false /* fromFullscreen */);
2661 }
2662 } finally {
2663 Binder.restoreCallingIdentity(ident);
2664 }
2665 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002666 /**
2667 * Moves the specified task to the primary-split-screen stack.
2668 *
2669 * @param taskId Id of task to move.
2670 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2671 * exist already. See
2672 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2673 * and
2674 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2675 * @param toTop If the task and stack should be moved to the top.
2676 * @param animate Whether we should play an animation for the moving the task.
2677 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2678 * stack. Pass {@code null} to use default bounds.
2679 * @param showRecents If the recents activity should be shown on the other side of the task
2680 * going into split-screen mode.
2681 */
2682 @Override
2683 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2684 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002685 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002686 "setTaskWindowingModeSplitScreenPrimary()");
2687 synchronized (mGlobalLock) {
2688 final long ident = Binder.clearCallingIdentity();
2689 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002690 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002691 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002692 if (task == null) {
2693 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2694 return false;
2695 }
2696 if (DEBUG_STACK) Slog.d(TAG_STACK,
2697 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2698 + " to createMode=" + createMode + " toTop=" + toTop);
2699 if (!task.isActivityTypeStandardOrUndefined()) {
2700 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2701 + " non-standard task " + taskId + " to split-screen windowing mode");
2702 }
2703
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002704 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 final int windowingMode = task.getWindowingMode();
2706 final ActivityStack stack = task.getStack();
2707 if (toTop) {
2708 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2709 }
2710 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002711 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2712 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 return windowingMode != task.getWindowingMode();
2714 } finally {
2715 Binder.restoreCallingIdentity(ident);
2716 }
2717 }
2718 }
2719
2720 /**
2721 * Removes stacks in the input windowing modes from the system if they are of activity type
2722 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2723 */
2724 @Override
2725 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002726 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 "removeStacksInWindowingModes()");
2728
2729 synchronized (mGlobalLock) {
2730 final long ident = Binder.clearCallingIdentity();
2731 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002732 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737 }
2738
2739 @Override
2740 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002741 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 "removeStacksWithActivityTypes()");
2743
2744 synchronized (mGlobalLock) {
2745 final long ident = Binder.clearCallingIdentity();
2746 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002747 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002748 } finally {
2749 Binder.restoreCallingIdentity(ident);
2750 }
2751 }
2752 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002753
2754 @Override
2755 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2756 int userId) {
2757 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002758 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2759 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002760 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002761 final boolean detailed = checkGetTasksPermission(
2762 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2763 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 == PackageManager.PERMISSION_GRANTED;
2765
2766 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002767 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 callingUid);
2769 }
2770 }
2771
2772 @Override
2773 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002774 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 long ident = Binder.clearCallingIdentity();
2776 try {
2777 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002778 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 }
2780 } finally {
2781 Binder.restoreCallingIdentity(ident);
2782 }
2783 }
2784
2785 @Override
2786 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002788 long ident = Binder.clearCallingIdentity();
2789 try {
2790 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002791 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002792 }
2793 } finally {
2794 Binder.restoreCallingIdentity(ident);
2795 }
2796 }
2797
2798 @Override
2799 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 final long callingUid = Binder.getCallingUid();
2802 final long origId = Binder.clearCallingIdentity();
2803 try {
2804 synchronized (mGlobalLock) {
2805 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002806 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002807 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2808 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2809 }
2810 } finally {
2811 Binder.restoreCallingIdentity(origId);
2812 }
2813 }
2814
2815 @Override
2816 public void startLockTaskModeByToken(IBinder token) {
2817 synchronized (mGlobalLock) {
2818 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2819 if (r == null) {
2820 return;
2821 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002822 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002823 }
2824 }
2825
2826 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002827 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002828 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002829 // This makes inner call to look as if it was initiated by system.
2830 long ident = Binder.clearCallingIdentity();
2831 try {
2832 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002833 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002834 MATCH_TASK_IN_STACKS_ONLY);
2835 if (task == null) {
2836 return;
2837 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838
2839 // When starting lock task mode the stack must be in front and focused
2840 task.getStack().moveToFront("startSystemLockTaskMode");
2841 startLockTaskModeLocked(task, true /* isSystemCaller */);
2842 }
2843 } finally {
2844 Binder.restoreCallingIdentity(ident);
2845 }
2846 }
2847
2848 @Override
2849 public void stopLockTaskModeByToken(IBinder token) {
2850 synchronized (mGlobalLock) {
2851 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2852 if (r == null) {
2853 return;
2854 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002855 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 }
2857 }
2858
2859 /**
2860 * This API should be called by SystemUI only when user perform certain action to dismiss
2861 * lock task mode. We should only dismiss pinned lock task mode in this case.
2862 */
2863 @Override
2864 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002865 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2867 }
2868
2869 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2870 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2871 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2872 return;
2873 }
2874
Wale Ogunwaled32da472018-11-16 07:19:28 -08002875 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 if (stack == null || task != stack.topTask()) {
2877 throw new IllegalArgumentException("Invalid task, not in foreground");
2878 }
2879
2880 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2881 // system or a specific app.
2882 // * System-initiated requests will only start the pinned mode (screen pinning)
2883 // * App-initiated requests
2884 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2885 // - will start the pinned mode, otherwise
2886 final int callingUid = Binder.getCallingUid();
2887 long ident = Binder.clearCallingIdentity();
2888 try {
2889 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002890 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002892 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893 } finally {
2894 Binder.restoreCallingIdentity(ident);
2895 }
2896 }
2897
2898 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2899 final int callingUid = Binder.getCallingUid();
2900 long ident = Binder.clearCallingIdentity();
2901 try {
2902 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002903 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002904 }
2905 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2906 // task and jumping straight into a call in the case of emergency call back.
2907 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2908 if (tm != null) {
2909 tm.showInCallScreen(false);
2910 }
2911 } finally {
2912 Binder.restoreCallingIdentity(ident);
2913 }
2914 }
2915
2916 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002917 public void updateLockTaskPackages(int userId, String[] packages) {
2918 final int callingUid = Binder.getCallingUid();
2919 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2920 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2921 "updateLockTaskPackages()");
2922 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002923 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002924 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2925 + Arrays.toString(packages));
2926 getLockTaskController().updateLockTaskPackages(userId, packages);
2927 }
2928 }
2929
2930 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 public boolean isInLockTaskMode() {
2932 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2933 }
2934
2935 @Override
2936 public int getLockTaskModeState() {
2937 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002938 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941
2942 @Override
2943 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2944 synchronized (mGlobalLock) {
2945 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2946 if (r != null) {
2947 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002948 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002950 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002951 }
2952 }
2953 }
2954
2955 @Override
2956 public Bundle getActivityOptions(IBinder token) {
2957 final long origId = Binder.clearCallingIdentity();
2958 try {
2959 synchronized (mGlobalLock) {
2960 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2961 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002962 final ActivityOptions activityOptions = r.takeOptionsLocked(
2963 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 return activityOptions == null ? null : activityOptions.toBundle();
2965 }
2966 return null;
2967 }
2968 } finally {
2969 Binder.restoreCallingIdentity(origId);
2970 }
2971 }
2972
2973 @Override
2974 public List<IBinder> getAppTasks(String callingPackage) {
2975 int callingUid = Binder.getCallingUid();
2976 long ident = Binder.clearCallingIdentity();
2977 try {
2978 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002979 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 }
2981 } finally {
2982 Binder.restoreCallingIdentity(ident);
2983 }
2984 }
2985
2986 @Override
2987 public void finishVoiceTask(IVoiceInteractionSession session) {
2988 synchronized (mGlobalLock) {
2989 final long origId = Binder.clearCallingIdentity();
2990 try {
2991 // TODO: VI Consider treating local voice interactions and voice tasks
2992 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002993 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 } finally {
2995 Binder.restoreCallingIdentity(origId);
2996 }
2997 }
2998
2999 }
3000
3001 @Override
3002 public boolean isTopOfTask(IBinder token) {
3003 synchronized (mGlobalLock) {
3004 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003005 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 }
3007 }
3008
3009 @Override
3010 public void notifyLaunchTaskBehindComplete(IBinder token) {
3011 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3012 }
3013
3014 @Override
3015 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003016 mH.post(() -> {
3017 synchronized (mGlobalLock) {
3018 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003019 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003020 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003021 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003022 } catch (RemoteException e) {
3023 }
3024 }
3025 }
3026
3027 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003028 }
3029
3030 /** Called from an app when assist data is ready. */
3031 @Override
3032 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3033 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003034 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 synchronized (pae) {
3036 pae.result = extras;
3037 pae.structure = structure;
3038 pae.content = content;
3039 if (referrer != null) {
3040 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3041 }
3042 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003043 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003044 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003045 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 structure.setHomeActivity(pae.isHome);
3047 }
3048 pae.haveResult = true;
3049 pae.notifyAll();
3050 if (pae.intent == null && pae.receiver == null) {
3051 // Caller is just waiting for the result.
3052 return;
3053 }
3054 }
3055 // We are now ready to launch the assist activity.
3056 IAssistDataReceiver sendReceiver = null;
3057 Bundle sendBundle = null;
3058 synchronized (mGlobalLock) {
3059 buildAssistBundleLocked(pae, extras);
3060 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003061 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 if (!exists) {
3063 // Timed out.
3064 return;
3065 }
3066
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003067 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 // Caller wants result sent back to them.
3069 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003070 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003071 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003072 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3073 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003074 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3075 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3076 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3077 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3078 }
3079 }
3080 if (sendReceiver != null) {
3081 try {
3082 sendReceiver.onHandleAssistData(sendBundle);
3083 } catch (RemoteException e) {
3084 }
3085 return;
3086 }
3087
3088 final long ident = Binder.clearCallingIdentity();
3089 try {
3090 if (TextUtils.equals(pae.intent.getAction(),
3091 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003092 // Start voice interaction through VoiceInteractionManagerService.
3093 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3094 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 } else {
3096 pae.intent.replaceExtras(pae.extras);
3097 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3098 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3099 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003100 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003101
3102 try {
3103 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3104 } catch (ActivityNotFoundException e) {
3105 Slog.w(TAG, "No activity to handle assist action.", e);
3106 }
3107 }
3108 } finally {
3109 Binder.restoreCallingIdentity(ident);
3110 }
3111 }
3112
3113 @Override
3114 public int addAppTask(IBinder activityToken, Intent intent,
3115 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3116 final int callingUid = Binder.getCallingUid();
3117 final long callingIdent = Binder.clearCallingIdentity();
3118
3119 try {
3120 synchronized (mGlobalLock) {
3121 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3122 if (r == null) {
3123 throw new IllegalArgumentException("Activity does not exist; token="
3124 + activityToken);
3125 }
3126 ComponentName comp = intent.getComponent();
3127 if (comp == null) {
3128 throw new IllegalArgumentException("Intent " + intent
3129 + " must specify explicit component");
3130 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003131 if (thumbnail.getWidth() != mThumbnailWidth
3132 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 throw new IllegalArgumentException("Bad thumbnail size: got "
3134 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003135 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003136 }
3137 if (intent.getSelector() != null) {
3138 intent.setSelector(null);
3139 }
3140 if (intent.getSourceBounds() != null) {
3141 intent.setSourceBounds(null);
3142 }
3143 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3144 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3145 // The caller has added this as an auto-remove task... that makes no
3146 // sense, so turn off auto-remove.
3147 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3148 }
3149 }
3150 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3151 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3152 if (ainfo.applicationInfo.uid != callingUid) {
3153 throw new SecurityException(
3154 "Can't add task for another application: target uid="
3155 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3156 }
3157
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003158 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003160 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003162 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 // The app has too many tasks already and we can't add any more
3164 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3165 return INVALID_TASK_ID;
3166 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003167 task.mTaskDescription.copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168
3169 // TODO: Send the thumbnail to WM to store it.
3170
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003171 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003172 }
3173 } finally {
3174 Binder.restoreCallingIdentity(callingIdent);
3175 }
3176 }
3177
3178 @Override
3179 public Point getAppTaskThumbnailSize() {
3180 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003181 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 }
3183 }
3184
3185 @Override
3186 public void setTaskResizeable(int taskId, int resizeableMode) {
3187 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003188 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3190 if (task == null) {
3191 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3192 return;
3193 }
3194 task.setResizeMode(resizeableMode);
3195 }
3196 }
3197
3198 @Override
3199 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 long ident = Binder.clearCallingIdentity();
3202 try {
3203 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003204 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003205 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 if (task == null) {
3207 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3208 return;
3209 }
3210 // Place the task in the right stack if it isn't there already based on
3211 // the requested bounds.
3212 // The stack transition logic is:
3213 // - a null bounds on a freeform task moves that task to fullscreen
3214 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3215 // that task to freeform
3216 // - otherwise the task is not moved
3217 ActivityStack stack = task.getStack();
3218 if (!task.getWindowConfiguration().canResizeTask()) {
3219 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3220 }
3221 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3222 stack = stack.getDisplay().getOrCreateStack(
3223 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3224 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3225 stack = stack.getDisplay().getOrCreateStack(
3226 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3227 }
3228
3229 // Reparent the task to the right stack if necessary
3230 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3231 if (stack != task.getStack()) {
3232 // Defer resume until the task is resized below
3233 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3234 DEFER_RESUME, "resizeTask");
3235 preserveWindow = false;
3236 }
3237
3238 // After reparenting (which only resizes the task to the stack bounds), resize the
3239 // task to the actual bounds provided
3240 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3241 }
3242 } finally {
3243 Binder.restoreCallingIdentity(ident);
3244 }
3245 }
3246
3247 @Override
3248 public boolean releaseActivityInstance(IBinder token) {
3249 synchronized (mGlobalLock) {
3250 final long origId = Binder.clearCallingIdentity();
3251 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003252 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3253 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 return false;
3255 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003256 r.destroyImmediately(true /* removeFromApp */, "app-req");
3257 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 } finally {
3259 Binder.restoreCallingIdentity(origId);
3260 }
3261 }
3262 }
3263
3264 @Override
3265 public void releaseSomeActivities(IApplicationThread appInt) {
3266 synchronized (mGlobalLock) {
3267 final long origId = Binder.clearCallingIdentity();
3268 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003269 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003270 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003271 } finally {
3272 Binder.restoreCallingIdentity(origId);
3273 }
3274 }
3275 }
3276
3277 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003278 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003279 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003280 != PackageManager.PERMISSION_GRANTED) {
3281 throw new SecurityException("Requires permission "
3282 + android.Manifest.permission.DEVICE_POWER);
3283 }
3284
3285 synchronized (mGlobalLock) {
3286 long ident = Binder.clearCallingIdentity();
3287 if (mKeyguardShown != keyguardShowing) {
3288 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003289 final Message msg = PooledLambda.obtainMessage(
3290 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3291 keyguardShowing);
3292 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 }
3294 try {
wilsonshih177261f2019-02-22 12:02:18 +08003295 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 } finally {
3297 Binder.restoreCallingIdentity(ident);
3298 }
3299 }
3300
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 mH.post(() -> {
3302 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3303 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3304 }
3305 });
3306 }
3307
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003308 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003309 mH.post(() -> {
3310 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3311 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3312 }
3313 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 }
3315
3316 @Override
3317 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003318 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3319 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320
3321 final File passedIconFile = new File(filePath);
3322 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3323 passedIconFile.getName());
3324 if (!legitIconFile.getPath().equals(filePath)
3325 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3326 throw new IllegalArgumentException("Bad file path: " + filePath
3327 + " passed for userId " + userId);
3328 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003329 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003330 }
3331
3332 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003334 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 synchronized (mGlobalLock) {
3336 final long ident = Binder.clearCallingIdentity();
3337 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003338 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003339 if (stack == null) {
3340 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3341 return;
3342 }
3343 if (!stack.isActivityTypeStandardOrUndefined()) {
3344 throw new IllegalArgumentException(
3345 "Removing non-standard stack is not allowed.");
3346 }
3347 mStackSupervisor.removeStack(stack);
3348 } finally {
3349 Binder.restoreCallingIdentity(ident);
3350 }
3351 }
3352 }
3353
3354 @Override
3355 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003356 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357
3358 synchronized (mGlobalLock) {
3359 final long ident = Binder.clearCallingIdentity();
3360 try {
3361 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3362 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003363 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003364 } finally {
3365 Binder.restoreCallingIdentity(ident);
3366 }
3367 }
3368 }
3369
3370 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003371 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 synchronized (mGlobalLock) {
3373 long ident = Binder.clearCallingIdentity();
3374 try {
3375 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3376 if (r == null) {
3377 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003378 "toggleFreeformWindowingMode: No activity record matching token="
3379 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 }
3381
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003382 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003383 if (stack == null) {
3384 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3385 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 }
3387
Yunfan Chend967af82019-01-17 18:30:18 +09003388 if (!stack.inFreeformWindowingMode()
3389 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3390 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3391 + "toggle between fullscreen and freeform.");
3392 }
3393
3394 if (stack.inFreeformWindowingMode()) {
3395 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003396 } else if (stack.getParent().inFreeformWindowingMode()) {
3397 // If the window is on a freeform display, set it to undefined. It will be
3398 // resolved to freeform and it can adjust windowing mode when the display mode
3399 // changes in runtime.
3400 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003401 } else {
3402 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 } finally {
3405 Binder.restoreCallingIdentity(ident);
3406 }
3407 }
3408 }
3409
3410 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3411 @Override
3412 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003413 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003415 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 }
3417
3418 /** Unregister a task stack listener so that it stops receiving callbacks. */
3419 @Override
3420 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003423 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 }
3425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 @Override
3427 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3428 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3429 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3430 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3431 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3432 }
3433
3434 @Override
3435 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3436 IBinder activityToken, int flags) {
3437 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3438 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3439 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3440 }
3441
3442 @Override
3443 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3444 Bundle args) {
3445 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3446 true /* focused */, true /* newSessionId */, userHandle, args,
3447 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3448 }
3449
3450 @Override
3451 public Bundle getAssistContextExtras(int requestType) {
3452 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3453 null, null, true /* focused */, true /* newSessionId */,
3454 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3455 if (pae == null) {
3456 return null;
3457 }
3458 synchronized (pae) {
3459 while (!pae.haveResult) {
3460 try {
3461 pae.wait();
3462 } catch (InterruptedException e) {
3463 }
3464 }
3465 }
3466 synchronized (mGlobalLock) {
3467 buildAssistBundleLocked(pae, pae.result);
3468 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003469 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 }
3471 return pae.extras;
3472 }
3473
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003474 /**
3475 * Binder IPC calls go through the public entry point.
3476 * This can be called with or without the global lock held.
3477 */
3478 private static int checkCallingPermission(String permission) {
3479 return checkPermission(
3480 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3481 }
3482
3483 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003484 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003485 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3486 mAmInternal.enforceCallingPermission(permission, func);
3487 }
3488 }
3489
3490 @VisibleForTesting
3491 int checkGetTasksPermission(String permission, int pid, int uid) {
3492 return checkPermission(permission, pid, uid);
3493 }
3494
3495 static int checkPermission(String permission, int pid, int uid) {
3496 if (permission == null) {
3497 return PackageManager.PERMISSION_DENIED;
3498 }
3499 return checkComponentPermission(permission, pid, uid, -1, true);
3500 }
3501
Wale Ogunwale214f3482018-10-04 11:00:47 -07003502 public static int checkComponentPermission(String permission, int pid, int uid,
3503 int owningUid, boolean exported) {
3504 return ActivityManagerService.checkComponentPermission(
3505 permission, pid, uid, owningUid, exported);
3506 }
3507
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003508 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3509 if (getRecentTasks().isCallerRecents(callingUid)) {
3510 // Always allow the recents component to get tasks
3511 return true;
3512 }
3513
3514 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3515 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3516 if (!allowed) {
3517 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3518 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3519 // Temporary compatibility: some existing apps on the system image may
3520 // still be requesting the old permission and not switched to the new
3521 // one; if so, we'll still allow them full access. This means we need
3522 // to see if they are holding the old permission and are a system app.
3523 try {
3524 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3525 allowed = true;
3526 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3527 + " is using old GET_TASKS but privileged; allowing");
3528 }
3529 } catch (RemoteException e) {
3530 }
3531 }
3532 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3533 + " does not hold REAL_GET_TASKS; limiting output");
3534 }
3535 return allowed;
3536 }
3537
Nicholas Sauer0259e532019-08-30 08:24:55 -07003538 boolean isCrossUserAllowed(int pid, int uid) {
3539 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3540 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3541 }
3542
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003543 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3544 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3545 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3546 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003547 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 "enqueueAssistContext()");
3549
3550 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003551 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 if (activity == null) {
3553 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3554 return null;
3555 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003556 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003557 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3558 return null;
3559 }
3560 if (focused) {
3561 if (activityToken != null) {
3562 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3563 if (activity != caller) {
3564 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3565 + " is not current top " + activity);
3566 return null;
3567 }
3568 }
3569 } else {
3570 activity = ActivityRecord.forTokenLocked(activityToken);
3571 if (activity == null) {
3572 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3573 + " couldn't be found");
3574 return null;
3575 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003576 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003577 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3578 return null;
3579 }
3580 }
3581
3582 PendingAssistExtras pae;
3583 Bundle extras = new Bundle();
3584 if (args != null) {
3585 extras.putAll(args);
3586 }
3587 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003588 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589
3590 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3591 userHandle);
3592 pae.isHome = activity.isActivityTypeHome();
3593
3594 // Increment the sessionId if necessary
3595 if (newSessionId) {
3596 mViSessionId++;
3597 }
3598 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003599 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3600 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003602 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 } catch (RemoteException e) {
3604 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3605 return null;
3606 }
3607 return pae;
3608 }
3609 }
3610
3611 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3612 if (result != null) {
3613 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3614 }
3615 if (pae.hint != null) {
3616 pae.extras.putBoolean(pae.hint, true);
3617 }
3618 }
3619
3620 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3621 IAssistDataReceiver receiver;
3622 synchronized (mGlobalLock) {
3623 mPendingAssistExtras.remove(pae);
3624 receiver = pae.receiver;
3625 }
3626 if (receiver != null) {
3627 // Caller wants result sent back to them.
3628 Bundle sendBundle = new Bundle();
3629 // At least return the receiver extras
3630 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3631 try {
3632 pae.receiver.onHandleAssistData(sendBundle);
3633 } catch (RemoteException e) {
3634 }
3635 }
3636 }
3637
3638 public class PendingAssistExtras extends Binder implements Runnable {
3639 public final ActivityRecord activity;
3640 public boolean isHome;
3641 public final Bundle extras;
3642 public final Intent intent;
3643 public final String hint;
3644 public final IAssistDataReceiver receiver;
3645 public final int userHandle;
3646 public boolean haveResult = false;
3647 public Bundle result = null;
3648 public AssistStructure structure = null;
3649 public AssistContent content = null;
3650 public Bundle receiverExtras;
3651
3652 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3653 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3654 int _userHandle) {
3655 activity = _activity;
3656 extras = _extras;
3657 intent = _intent;
3658 hint = _hint;
3659 receiver = _receiver;
3660 receiverExtras = _receiverExtras;
3661 userHandle = _userHandle;
3662 }
3663
3664 @Override
3665 public void run() {
3666 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3667 synchronized (this) {
3668 haveResult = true;
3669 notifyAll();
3670 }
3671 pendingAssistExtrasTimedOut(this);
3672 }
3673 }
3674
3675 @Override
3676 public boolean isAssistDataAllowedOnCurrentActivity() {
3677 int userId;
3678 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003679 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003680 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3681 return false;
3682 }
3683
3684 final ActivityRecord activity = focusedStack.getTopActivity();
3685 if (activity == null) {
3686 return false;
3687 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003688 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 }
3690 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3691 }
3692
3693 @Override
3694 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3695 long ident = Binder.clearCallingIdentity();
3696 try {
3697 synchronized (mGlobalLock) {
3698 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003699 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003700 if (top != caller) {
3701 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3702 + " is not current top " + top);
3703 return false;
3704 }
3705 if (!top.nowVisible) {
3706 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3707 + " is not visible");
3708 return false;
3709 }
3710 }
3711 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3712 token);
3713 } finally {
3714 Binder.restoreCallingIdentity(ident);
3715 }
3716 }
3717
3718 @Override
3719 public boolean isRootVoiceInteraction(IBinder token) {
3720 synchronized (mGlobalLock) {
3721 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3722 if (r == null) {
3723 return false;
3724 }
3725 return r.rootVoiceInteraction;
3726 }
3727 }
3728
Wale Ogunwalef6733932018-06-27 05:14:34 -07003729 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3730 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3731 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3732 if (activityToCallback == null) return;
3733 activityToCallback.setVoiceSessionLocked(voiceSession);
3734
3735 // Inform the activity
3736 try {
3737 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3738 voiceInteractor);
3739 long token = Binder.clearCallingIdentity();
3740 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003741 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003742 } finally {
3743 Binder.restoreCallingIdentity(token);
3744 }
3745 // TODO: VI Should we cache the activity so that it's easier to find later
3746 // rather than scan through all the stacks and activities?
3747 } catch (RemoteException re) {
3748 activityToCallback.clearVoiceSessionLocked();
3749 // TODO: VI Should this terminate the voice session?
3750 }
3751 }
3752
3753 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3754 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3755 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3756 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3757 boolean wasRunningVoice = mRunningVoice != null;
3758 mRunningVoice = session;
3759 if (!wasRunningVoice) {
3760 mVoiceWakeLock.acquire();
3761 updateSleepIfNeededLocked();
3762 }
3763 }
3764 }
3765
3766 void finishRunningVoiceLocked() {
3767 if (mRunningVoice != null) {
3768 mRunningVoice = null;
3769 mVoiceWakeLock.release();
3770 updateSleepIfNeededLocked();
3771 }
3772 }
3773
3774 @Override
3775 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3776 synchronized (mGlobalLock) {
3777 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3778 if (keepAwake) {
3779 mVoiceWakeLock.acquire();
3780 } else {
3781 mVoiceWakeLock.release();
3782 }
3783 }
3784 }
3785 }
3786
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003787 @Override
3788 public ComponentName getActivityClassForToken(IBinder token) {
3789 synchronized (mGlobalLock) {
3790 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3791 if (r == null) {
3792 return null;
3793 }
3794 return r.intent.getComponent();
3795 }
3796 }
3797
3798 @Override
3799 public String getPackageForToken(IBinder token) {
3800 synchronized (mGlobalLock) {
3801 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3802 if (r == null) {
3803 return null;
3804 }
3805 return r.packageName;
3806 }
3807 }
3808
3809 @Override
3810 public void showLockTaskEscapeMessage(IBinder token) {
3811 synchronized (mGlobalLock) {
3812 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3813 if (r == null) {
3814 return;
3815 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003816 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 }
3818 }
3819
3820 @Override
3821 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003822 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 final long token = Binder.clearCallingIdentity();
3824 try {
3825 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003826 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827 }
3828 } finally {
3829 Binder.restoreCallingIdentity(token);
3830 }
3831 }
3832
3833 /**
3834 * Try to place task to provided position. The final position might be different depending on
3835 * current user and stacks state. The task will be moved to target stack if it's currently in
3836 * different stack.
3837 */
3838 @Override
3839 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003840 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 synchronized (mGlobalLock) {
3842 long ident = Binder.clearCallingIdentity();
3843 try {
3844 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3845 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003846 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 if (task == null) {
3848 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3849 + taskId);
3850 }
3851
Wale Ogunwaled32da472018-11-16 07:19:28 -08003852 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853
3854 if (stack == null) {
3855 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3856 + stackId);
3857 }
3858 if (!stack.isActivityTypeStandardOrUndefined()) {
3859 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3860 + " the position of task " + taskId + " in/to non-standard stack");
3861 }
3862
3863 // TODO: Have the callers of this API call a separate reparent method if that is
3864 // what they intended to do vs. having this method also do reparenting.
3865 if (task.getStack() == stack) {
3866 // Change position in current stack.
3867 stack.positionChildAt(task, position);
3868 } else {
3869 // Reparent to new stack.
3870 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3871 !DEFER_RESUME, "positionTaskInStack");
3872 }
3873 } finally {
3874 Binder.restoreCallingIdentity(ident);
3875 }
3876 }
3877 }
3878
3879 @Override
3880 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3881 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3882 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003883 + Arrays.toString(horizontalSizeConfiguration) + " "
3884 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003885 synchronized (mGlobalLock) {
3886 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3887 if (record == null) {
3888 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3889 + "found for: " + token);
3890 }
3891 record.setSizeConfigurations(horizontalSizeConfiguration,
3892 verticalSizeConfigurations, smallestSizeConfigurations);
3893 }
3894 }
3895
3896 /**
3897 * Dismisses split-screen multi-window mode.
3898 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3899 */
3900 @Override
3901 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003902 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003903 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3904 final long ident = Binder.clearCallingIdentity();
3905 try {
3906 synchronized (mGlobalLock) {
3907 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003908 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 if (stack == null) {
3910 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3911 return;
3912 }
3913
3914 if (toTop) {
3915 // Caller wants the current split-screen primary stack to be the top stack after
3916 // it goes fullscreen, so move it to the front.
3917 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003918 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003920 // stack after it goes fullscreen, so we move the focus to the top-most
3921 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3923 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3924 if (otherStack != null) {
3925 otherStack.moveToFront("dismissSplitScreenMode_other");
3926 }
3927 }
3928
Evan Rosky10475742018-09-05 19:02:48 -07003929 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 }
3931 } finally {
3932 Binder.restoreCallingIdentity(ident);
3933 }
3934 }
3935
3936 /**
3937 * Dismisses Pip
3938 * @param animate True if the dismissal should be animated.
3939 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3940 * default animation duration should be used.
3941 */
3942 @Override
3943 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003944 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 final long ident = Binder.clearCallingIdentity();
3946 try {
3947 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003948 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003949 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 if (stack == null) {
3951 Slog.w(TAG, "dismissPip: pinned stack not found.");
3952 return;
3953 }
3954 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3955 throw new IllegalArgumentException("Stack: " + stack
3956 + " doesn't support animated resize.");
3957 }
3958 if (animate) {
3959 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3960 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3961 } else {
3962 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3963 }
3964 }
3965 } finally {
3966 Binder.restoreCallingIdentity(ident);
3967 }
3968 }
3969
3970 @Override
3971 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003972 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 synchronized (mGlobalLock) {
3974 mSuppressResizeConfigChanges = suppress;
3975 }
3976 }
3977
3978 /**
3979 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3980 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3981 * activity and clearing the task at the same time.
3982 */
3983 @Override
3984 // TODO: API should just be about changing windowing modes...
3985 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 "moveTasksToFullscreenStack()");
3988 synchronized (mGlobalLock) {
3989 final long origId = Binder.clearCallingIdentity();
3990 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003991 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 if (stack != null){
3993 if (!stack.isActivityTypeStandardOrUndefined()) {
3994 throw new IllegalArgumentException(
3995 "You can't move tasks from non-standard stacks.");
3996 }
3997 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3998 }
3999 } finally {
4000 Binder.restoreCallingIdentity(origId);
4001 }
4002 }
4003 }
4004
4005 /**
4006 * Moves the top activity in the input stackId to the pinned stack.
4007 *
4008 * @param stackId Id of stack to move the top activity to pinned stack.
4009 * @param bounds Bounds to use for pinned stack.
4010 *
4011 * @return True if the top activity of the input stack was successfully moved to the pinned
4012 * stack.
4013 */
4014 @Override
4015 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004016 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 "moveTopActivityToPinnedStack()");
4018 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004019 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4021 + "Device doesn't support picture-in-picture mode");
4022 }
4023
4024 long ident = Binder.clearCallingIdentity();
4025 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004026 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 } finally {
4028 Binder.restoreCallingIdentity(ident);
4029 }
4030 }
4031 }
4032
4033 @Override
4034 public boolean isInMultiWindowMode(IBinder token) {
4035 final long origId = Binder.clearCallingIdentity();
4036 try {
4037 synchronized (mGlobalLock) {
4038 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4039 if (r == null) {
4040 return false;
4041 }
4042 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4043 return r.inMultiWindowMode();
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(origId);
4047 }
4048 }
4049
4050 @Override
4051 public boolean isInPictureInPictureMode(IBinder token) {
4052 final long origId = Binder.clearCallingIdentity();
4053 try {
4054 synchronized (mGlobalLock) {
4055 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4056 }
4057 } finally {
4058 Binder.restoreCallingIdentity(origId);
4059 }
4060 }
4061
4062 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004063 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4064 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 return false;
4066 }
4067
4068 // If we are animating to fullscreen then we have already dispatched the PIP mode
4069 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004070 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4071 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 }
4073
4074 @Override
4075 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4076 final long origId = Binder.clearCallingIdentity();
4077 try {
4078 synchronized (mGlobalLock) {
4079 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4080 "enterPictureInPictureMode", token, params);
4081
4082 // If the activity is already in picture in picture mode, then just return early
4083 if (isInPictureInPictureMode(r)) {
4084 return true;
4085 }
4086
4087 // Activity supports picture-in-picture, now check that we can enter PiP at this
4088 // point, if it is
4089 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4090 false /* beforeStopping */)) {
4091 return false;
4092 }
4093
4094 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004095 synchronized (mGlobalLock) {
4096 // Only update the saved args from the args that are set
4097 r.pictureInPictureArgs.copyOnlySet(params);
4098 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4099 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4100 // Adjust the source bounds by the insets for the transition down
4101 final Rect sourceBounds = new Rect(
4102 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004103 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004104 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004105 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004106 stack.setPictureInPictureAspectRatio(aspectRatio);
4107 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004108 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4109 r.info.applicationInfo.uid, r.shortComponentName,
4110 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004111 logPictureInPictureArgs(params);
4112 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 };
4114
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004115 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 // If the keyguard is showing or occluded, then try and dismiss it before
4117 // entering picture-in-picture (this will prompt the user to authenticate if the
4118 // device is currently locked).
4119 dismissKeyguard(token, new KeyguardDismissCallback() {
4120 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004121 public void onDismissSucceeded() {
4122 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 }
4124 }, null /* message */);
4125 } else {
4126 // Enter picture in picture immediately otherwise
4127 enterPipRunnable.run();
4128 }
4129 return true;
4130 }
4131 } finally {
4132 Binder.restoreCallingIdentity(origId);
4133 }
4134 }
4135
4136 @Override
4137 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4138 final long origId = Binder.clearCallingIdentity();
4139 try {
4140 synchronized (mGlobalLock) {
4141 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4142 "setPictureInPictureParams", token, params);
4143
4144 // Only update the saved args from the args that are set
4145 r.pictureInPictureArgs.copyOnlySet(params);
4146 if (r.inPinnedWindowingMode()) {
4147 // If the activity is already in picture-in-picture, update the pinned stack now
4148 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4149 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004150 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 if (!stack.isAnimatingBoundsToFullscreen()) {
4152 stack.setPictureInPictureAspectRatio(
4153 r.pictureInPictureArgs.getAspectRatio());
4154 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4155 }
4156 }
4157 logPictureInPictureArgs(params);
4158 }
4159 } finally {
4160 Binder.restoreCallingIdentity(origId);
4161 }
4162 }
4163
4164 @Override
4165 public int getMaxNumPictureInPictureActions(IBinder token) {
4166 // Currently, this is a static constant, but later, we may change this to be dependent on
4167 // the context of the activity
4168 return 3;
4169 }
4170
4171 private void logPictureInPictureArgs(PictureInPictureParams params) {
4172 if (params.hasSetActions()) {
4173 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4174 params.getActions().size());
4175 }
4176 if (params.hasSetAspectRatio()) {
4177 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4178 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4179 MetricsLogger.action(lm);
4180 }
4181 }
4182
4183 /**
4184 * Checks the state of the system and the activity associated with the given {@param token} to
4185 * verify that picture-in-picture is supported for that activity.
4186 *
4187 * @return the activity record for the given {@param token} if all the checks pass.
4188 */
4189 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4190 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 throw new IllegalStateException(caller
4193 + ": Device doesn't support picture-in-picture mode.");
4194 }
4195
4196 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4197 if (r == null) {
4198 throw new IllegalStateException(caller
4199 + ": Can't find activity for token=" + token);
4200 }
4201
4202 if (!r.supportsPictureInPicture()) {
4203 throw new IllegalStateException(caller
4204 + ": Current activity does not support picture-in-picture.");
4205 }
4206
4207 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004208 && !mWindowManager.isValidPictureInPictureAspectRatio(
4209 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 final float minAspectRatio = mContext.getResources().getFloat(
4211 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4212 final float maxAspectRatio = mContext.getResources().getFloat(
4213 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4214 throw new IllegalArgumentException(String.format(caller
4215 + ": Aspect ratio is too extreme (must be between %f and %f).",
4216 minAspectRatio, maxAspectRatio));
4217 }
4218
4219 // Truncate the number of actions if necessary
4220 params.truncateActions(getMaxNumPictureInPictureActions(token));
4221
4222 return r;
4223 }
4224
4225 @Override
4226 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004227 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 synchronized (mGlobalLock) {
4229 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4230 if (r == null) {
4231 throw new IllegalArgumentException("Activity does not exist; token="
4232 + activityToken);
4233 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004234 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004235 }
4236 }
4237
4238 @Override
4239 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4240 Rect tempDockedTaskInsetBounds,
4241 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 long ident = Binder.clearCallingIdentity();
4244 try {
4245 synchronized (mGlobalLock) {
4246 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4247 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4248 PRESERVE_WINDOWS);
4249 }
4250 } finally {
4251 Binder.restoreCallingIdentity(ident);
4252 }
4253 }
4254
4255 @Override
4256 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004257 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 final long ident = Binder.clearCallingIdentity();
4259 try {
4260 synchronized (mGlobalLock) {
4261 mStackSupervisor.setSplitScreenResizing(resizing);
4262 }
4263 } finally {
4264 Binder.restoreCallingIdentity(ident);
4265 }
4266 }
4267
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004268 /**
4269 * Check that we have the features required for VR-related API calls, and throw an exception if
4270 * not.
4271 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004272 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 if (!mContext.getPackageManager().hasSystemFeature(
4274 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4275 throw new UnsupportedOperationException("VR mode not supported on this device!");
4276 }
4277 }
4278
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004279 @Override
4280 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004281 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282
4283 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4284
4285 ActivityRecord r;
4286 synchronized (mGlobalLock) {
4287 r = ActivityRecord.isInStackLocked(token);
4288 }
4289
4290 if (r == null) {
4291 throw new IllegalArgumentException();
4292 }
4293
4294 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004295 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 VrManagerInternal.NO_ERROR) {
4297 return err;
4298 }
4299
4300 // Clear the binder calling uid since this path may call moveToTask().
4301 final long callingId = Binder.clearCallingIdentity();
4302 try {
4303 synchronized (mGlobalLock) {
4304 r.requestedVrComponent = (enabled) ? packageName : null;
4305
4306 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004307 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004308 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 }
4310 return 0;
4311 }
4312 } finally {
4313 Binder.restoreCallingIdentity(callingId);
4314 }
4315 }
4316
4317 @Override
4318 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4319 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4320 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004321 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004322 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4323 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4324 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004325 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004326 || activity.voiceSession != null) {
4327 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4328 return;
4329 }
4330 if (activity.pendingVoiceInteractionStart) {
4331 Slog.w(TAG, "Pending start of voice interaction already.");
4332 return;
4333 }
4334 activity.pendingVoiceInteractionStart = true;
4335 }
4336 LocalServices.getService(VoiceInteractionManagerInternal.class)
4337 .startLocalVoiceInteraction(callingActivity, options);
4338 }
4339
4340 @Override
4341 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4342 LocalServices.getService(VoiceInteractionManagerInternal.class)
4343 .stopLocalVoiceInteraction(callingActivity);
4344 }
4345
4346 @Override
4347 public boolean supportsLocalVoiceInteraction() {
4348 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4349 .supportsLocalVoiceInteraction();
4350 }
4351
4352 /** Notifies all listeners when the pinned stack animation starts. */
4353 @Override
4354 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004355 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 }
4357
4358 /** Notifies all listeners when the pinned stack animation ends. */
4359 @Override
4360 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363
4364 @Override
4365 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 final long ident = Binder.clearCallingIdentity();
4368 try {
4369 synchronized (mGlobalLock) {
4370 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4371 }
4372 } finally {
4373 Binder.restoreCallingIdentity(ident);
4374 }
4375 }
4376
4377 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380
4381 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004382 if (mWindowManager == null) {
4383 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4384 return false;
4385 }
4386
4387 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 }
4391
Riddle Hsua0022cd2019-09-09 21:12:41 +08004392 mH.sendMessage(PooledLambda.obtainMessage(
4393 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4394 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395
4396 final long origId = Binder.clearCallingIdentity();
4397 try {
4398 if (values != null) {
4399 Settings.System.clearConfiguration(values);
4400 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004401 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 UserHandle.USER_NULL, false /* deferResume */,
4403 mTmpUpdateConfigurationResult);
4404 return mTmpUpdateConfigurationResult.changes != 0;
4405 } finally {
4406 Binder.restoreCallingIdentity(origId);
4407 }
4408 }
4409 }
4410
4411 @Override
4412 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4413 CharSequence message) {
4414 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004415 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4417 }
4418 final long callingId = Binder.clearCallingIdentity();
4419 try {
4420 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 }
4423 } finally {
4424 Binder.restoreCallingIdentity(callingId);
4425 }
4426 }
4427
4428 @Override
4429 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 "cancelTaskWindowTransition()");
4432 final long ident = Binder.clearCallingIdentity();
4433 try {
4434 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004435 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 MATCH_TASK_IN_STACKS_ONLY);
4437 if (task == null) {
4438 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4439 return;
4440 }
4441 task.cancelWindowTransition();
4442 }
4443 } finally {
4444 Binder.restoreCallingIdentity(ident);
4445 }
4446 }
4447
4448 @Override
4449 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 final long ident = Binder.clearCallingIdentity();
4452 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004453 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 } finally {
4455 Binder.restoreCallingIdentity(ident);
4456 }
4457 }
4458
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004459 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4460 boolean restoreFromDisk) {
4461 final TaskRecord task;
4462 synchronized (mGlobalLock) {
4463 task = mRootActivityContainer.anyTaskForId(taskId,
4464 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4465 if (task == null) {
4466 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4467 return null;
4468 }
4469 }
4470 // Don't call this while holding the lock as this operation might hit the disk.
4471 return task.getSnapshot(reducedResolution, restoreFromDisk);
4472 }
4473
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 @Override
4475 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4476 synchronized (mGlobalLock) {
4477 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4478 if (r == null) {
4479 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4480 + token);
4481 return;
4482 }
4483 final long origId = Binder.clearCallingIdentity();
4484 try {
4485 r.setDisablePreviewScreenshots(disable);
4486 } finally {
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489 }
4490 }
4491
4492 /** Return the user id of the last resumed activity. */
4493 @Override
4494 public @UserIdInt
4495 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4498 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004499 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004502 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 }
4504 }
4505
4506 @Override
4507 public void updateLockTaskFeatures(int userId, int flags) {
4508 final int callingUid = Binder.getCallingUid();
4509 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 "updateLockTaskFeatures()");
4512 }
4513 synchronized (mGlobalLock) {
4514 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4515 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004516 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 return;
4526 }
4527 final long origId = Binder.clearCallingIdentity();
4528 try {
4529 r.setShowWhenLocked(showWhenLocked);
4530 } finally {
4531 Binder.restoreCallingIdentity(origId);
4532 }
4533 }
4534 }
4535
4536 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004537 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null) {
4541 return;
4542 }
4543 final long origId = Binder.clearCallingIdentity();
4544 try {
4545 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4546 } finally {
4547 Binder.restoreCallingIdentity(origId);
4548 }
4549 }
4550 }
4551
4552 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4554 synchronized (mGlobalLock) {
4555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4556 if (r == null) {
4557 return;
4558 }
4559 final long origId = Binder.clearCallingIdentity();
4560 try {
4561 r.setTurnScreenOn(turnScreenOn);
4562 } finally {
4563 Binder.restoreCallingIdentity(origId);
4564 }
4565 }
4566 }
4567
4568 @Override
4569 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004570 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004572 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 synchronized (mGlobalLock) {
4574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4575 if (r == null) {
4576 return;
4577 }
4578 final long origId = Binder.clearCallingIdentity();
4579 try {
4580 r.registerRemoteAnimations(definition);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
4588 public void registerRemoteAnimationForNextActivityStart(String packageName,
4589 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004592 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004593 synchronized (mGlobalLock) {
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004596 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 packageName, adapter);
4598 } finally {
4599 Binder.restoreCallingIdentity(origId);
4600 }
4601 }
4602 }
4603
Evan Rosky966759f2019-01-15 10:33:58 -08004604 @Override
4605 public void registerRemoteAnimationsForDisplay(int displayId,
4606 RemoteAnimationDefinition definition) {
4607 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4608 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004609 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004610 synchronized (mGlobalLock) {
4611 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4612 if (display == null) {
4613 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 display.mDisplayContent.registerRemoteAnimations(definition);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004625 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4626 @Override
4627 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4628 synchronized (mGlobalLock) {
4629 final long origId = Binder.clearCallingIdentity();
4630 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004631 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 } finally {
4633 Binder.restoreCallingIdentity(origId);
4634 }
4635 }
4636 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004637
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004638 @Override
4639 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004642 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004643 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004644 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004645 }
4646 }
4647
4648 @Override
4649 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004651 != PERMISSION_GRANTED) {
4652 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4653 + Binder.getCallingPid()
4654 + ", uid=" + Binder.getCallingUid()
4655 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4656 Slog.w(TAG, msg);
4657 throw new SecurityException(msg);
4658 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004659 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004660 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004661 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004662 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004663 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 }
4665 }
4666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004667 @Override
4668 public void stopAppSwitches() {
4669 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4670 synchronized (mGlobalLock) {
4671 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004672 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 mDidAppSwitch = false;
4674 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4675 }
4676 }
4677
4678 @Override
4679 public void resumeAppSwitches() {
4680 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4681 synchronized (mGlobalLock) {
4682 // Note that we don't execute any pending app switches... we will
4683 // let those wait until either the timeout, or the next start
4684 // activity request.
4685 mAppSwitchesAllowedTime = 0;
4686 }
4687 }
4688
Ricky Wai906af482019-06-03 17:25:28 +01004689 long getLastStopAppSwitchesTime() {
4690 return mLastStopAppSwitchesTime;
4691 }
4692
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004693 void onStartActivitySetDidAppSwitch() {
4694 if (mDidAppSwitch) {
4695 // This is the second allowed switch since we stopped switches, so now just generally
4696 // allow switches. Use case:
4697 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4698 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4699 // anyone to switch again).
4700 mAppSwitchesAllowedTime = 0;
4701 } else {
4702 mDidAppSwitch = true;
4703 }
4704 }
4705
4706 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 boolean shouldDisableNonVrUiLocked() {
4708 return mVrController.shouldDisableNonVrUiLocked();
4709 }
4710
Wale Ogunwale53783742018-09-16 10:21:51 -07004711 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 // 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 +00004713 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004714 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004715 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4716 + " to main display for VR");
4717 mRootActivityContainer.moveStackToDisplay(
4718 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 }
4720 mH.post(() -> {
4721 if (!mVrController.onVrModeChanged(r)) {
4722 return;
4723 }
4724 synchronized (mGlobalLock) {
4725 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4726 mWindowManager.disableNonVrUi(disableNonVrUi);
4727 if (disableNonVrUi) {
4728 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4729 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004730 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732 }
4733 });
4734 }
4735
Wale Ogunwale53783742018-09-16 10:21:51 -07004736 @Override
4737 public int getPackageScreenCompatMode(String packageName) {
4738 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4739 synchronized (mGlobalLock) {
4740 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4741 }
4742 }
4743
4744 @Override
4745 public void setPackageScreenCompatMode(String packageName, int mode) {
4746 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4747 "setPackageScreenCompatMode");
4748 synchronized (mGlobalLock) {
4749 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4750 }
4751 }
4752
4753 @Override
4754 public boolean getPackageAskScreenCompat(String packageName) {
4755 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4756 synchronized (mGlobalLock) {
4757 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4758 }
4759 }
4760
4761 @Override
4762 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4763 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4764 "setPackageAskScreenCompat");
4765 synchronized (mGlobalLock) {
4766 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4767 }
4768 }
4769
Wale Ogunwale64258362018-10-16 15:13:37 -07004770 public static String relaunchReasonToString(int relaunchReason) {
4771 switch (relaunchReason) {
4772 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4773 return "window_resize";
4774 case RELAUNCH_REASON_FREE_RESIZE:
4775 return "free_resize";
4776 default:
4777 return null;
4778 }
4779 }
4780
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004781 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004782 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004783 }
4784
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 /** Pokes the task persister. */
4786 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4787 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4788 }
4789
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 boolean isKeyguardLocked() {
4791 return mKeyguardController.isKeyguardLocked();
4792 }
4793
Garfield Tan01548632018-11-27 10:15:48 -08004794 /**
4795 * Clears launch params for the given package.
4796 * @param packageNames the names of the packages of which the launch params are to be cleared
4797 */
4798 @Override
4799 public void clearLaunchParamsForPackages(List<String> packageNames) {
4800 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4801 "clearLaunchParamsForPackages");
4802 synchronized (mGlobalLock) {
4803 for (int i = 0; i < packageNames.size(); ++i) {
4804 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4805 }
4806 }
4807 }
4808
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004809 /**
4810 * Makes the display with the given id a single task instance display. I.e the display can only
4811 * contain one task.
4812 */
4813 @Override
4814 public void setDisplayToSingleTaskInstance(int displayId) {
4815 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4816 "setDisplayToSingleTaskInstance");
4817 final long origId = Binder.clearCallingIdentity();
4818 try {
4819 final ActivityDisplay display =
4820 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4821 if (display != null) {
4822 display.setDisplayToSingleTaskInstance();
4823 }
4824 } finally {
4825 Binder.restoreCallingIdentity(origId);
4826 }
4827 }
4828
Wale Ogunwale31913b52018-10-13 08:29:31 -07004829 void dumpLastANRLocked(PrintWriter pw) {
4830 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4831 if (mLastANRState == null) {
4832 pw.println(" <no ANR has occurred since boot>");
4833 } else {
4834 pw.println(mLastANRState);
4835 }
4836 }
4837
4838 void dumpLastANRTracesLocked(PrintWriter pw) {
4839 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4840
4841 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4842 if (ArrayUtils.isEmpty(files)) {
4843 pw.println(" <no ANR has occurred since boot>");
4844 return;
4845 }
4846 // Find the latest file.
4847 File latest = null;
4848 for (File f : files) {
4849 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4850 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004851 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004852 }
4853 pw.print("File: ");
4854 pw.print(latest.getName());
4855 pw.println();
4856 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4857 String line;
4858 while ((line = in.readLine()) != null) {
4859 pw.println(line);
4860 }
4861 } catch (IOException e) {
4862 pw.print("Unable to read: ");
4863 pw.print(e);
4864 pw.println();
4865 }
4866 }
4867
4868 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4869 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4870 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4871 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4872 }
4873
4874 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4875 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4876 pw.println(header);
4877
Wale Ogunwaled32da472018-11-16 07:19:28 -08004878 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004879 dumpPackage);
4880 boolean needSep = printedAnything;
4881
4882 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004883 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004884 " ResumedActivity: ");
4885 if (printed) {
4886 printedAnything = true;
4887 needSep = false;
4888 }
4889
4890 if (dumpPackage == null) {
4891 if (needSep) {
4892 pw.println();
4893 }
4894 printedAnything = true;
4895 mStackSupervisor.dump(pw, " ");
4896 }
4897
4898 if (!printedAnything) {
4899 pw.println(" (nothing)");
4900 }
4901 }
4902
4903 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004904 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004905 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004906 pw.println(" ");
4907 }
4908
4909 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4910 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4911 getActivityStartController().dump(pw, "", dumpPackage);
4912 }
4913
4914 /**
4915 * There are three things that cmd can be:
4916 * - a flattened component name that matches an existing activity
4917 * - the cmd arg isn't the flattened component name of an existing activity:
4918 * dump all activity whose component contains the cmd as a substring
4919 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004920 * <p>
4921 * The caller should not hold lock when calling this method because it will wait for the
4922 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004923 *
4924 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4925 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4926 */
4927 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4928 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4929 ArrayList<ActivityRecord> activities;
4930
4931 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004932 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004933 dumpFocusedStackOnly);
4934 }
4935
4936 if (activities.size() <= 0) {
4937 return false;
4938 }
4939
4940 String[] newArgs = new String[args.length - opti];
4941 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4942
4943 TaskRecord lastTask = null;
4944 boolean needSep = false;
4945 for (int i = activities.size() - 1; i >= 0; i--) {
4946 ActivityRecord r = activities.get(i);
4947 if (needSep) {
4948 pw.println();
4949 }
4950 needSep = true;
4951 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004952 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004953 if (lastTask != task) {
4954 lastTask = task;
4955 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004956 pw.print(" id="); pw.print(lastTask.mTaskId);
4957 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004958 if (dumpAll) {
4959 lastTask.dump(pw, " ");
4960 }
4961 }
4962 }
4963 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4964 }
4965 return true;
4966 }
4967
4968 /**
4969 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4970 * there is a thread associated with the activity.
4971 */
4972 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4973 final ActivityRecord r, String[] args, boolean dumpAll) {
4974 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004975 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004976 synchronized (mGlobalLock) {
4977 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4978 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4979 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004980 if (r.hasProcess()) {
4981 pw.println(r.app.getPid());
4982 appThread = r.app.getThread();
4983 } else {
4984 pw.println("(not running)");
4985 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004986 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07004987 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004988 }
4989 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004990 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004991 // flush anything that is already in the PrintWriter since the thread is going
4992 // to write to the file descriptor directly
4993 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004994 try (TransferPipe tp = new TransferPipe()) {
4995 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4996 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 } catch (IOException e) {
4998 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4999 } catch (RemoteException e) {
5000 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5001 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005002 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005003 }
5004
sanryhuang498e77e2018-12-06 14:57:01 +08005005 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5006 boolean testPssMode) {
5007 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5008 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5009 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005010 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005011 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5012 st.toString());
5013 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5016 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005017 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5018 testPssMode);
5019 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005020 }
5021
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005022 int getCurrentUserId() {
5023 return mAmInternal.getCurrentUserId();
5024 }
5025
5026 private void enforceNotIsolatedCaller(String caller) {
5027 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5028 throw new SecurityException("Isolated process not allowed to call " + caller);
5029 }
5030 }
5031
Wale Ogunwalef6733932018-06-27 05:14:34 -07005032 public Configuration getConfiguration() {
5033 Configuration ci;
5034 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005035 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005036 ci.userSetLocale = false;
5037 }
5038 return ci;
5039 }
5040
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005041 /**
5042 * Current global configuration information. Contains general settings for the entire system,
5043 * also corresponds to the merged configuration of the default display.
5044 */
5045 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005046 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005047 }
5048
5049 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5050 boolean initLocale) {
5051 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5052 }
5053
5054 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5055 boolean initLocale, boolean deferResume) {
5056 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5057 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5058 UserHandle.USER_NULL, deferResume);
5059 }
5060
Wale Ogunwale59507092018-10-29 09:00:30 -07005061 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005062 final long origId = Binder.clearCallingIdentity();
5063 try {
5064 synchronized (mGlobalLock) {
5065 updateConfigurationLocked(values, null, false, true, userId,
5066 false /* deferResume */);
5067 }
5068 } finally {
5069 Binder.restoreCallingIdentity(origId);
5070 }
5071 }
5072
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5074 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5075 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5076 deferResume, null /* result */);
5077 }
5078
5079 /**
5080 * Do either or both things: (1) change the current configuration, and (2)
5081 * make sure the given activity is running with the (now) current
5082 * configuration. Returns true if the activity has been left running, or
5083 * false if <var>starting</var> is being destroyed to match the new
5084 * configuration.
5085 *
5086 * @param userId is only used when persistent parameter is set to true to persist configuration
5087 * for that particular user
5088 */
5089 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5090 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5091 ActivityTaskManagerService.UpdateConfigurationResult result) {
5092 int changes = 0;
5093 boolean kept = true;
5094
Riddle Hsua0022cd2019-09-09 21:12:41 +08005095 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005096 try {
5097 if (values != null) {
5098 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5099 deferResume);
5100 }
5101
5102 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5103 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005104 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 }
5106
5107 if (result != null) {
5108 result.changes = changes;
5109 result.activityRelaunched = !kept;
5110 }
5111 return kept;
5112 }
5113
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005114 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005115 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005116 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005117
5118 final ActivityDisplay defaultDisplay =
5119 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5120
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005121 mTempConfig.setTo(getGlobalConfiguration());
5122 final int changes = mTempConfig.updateFrom(values);
5123 if (changes == 0) {
5124 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5125 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5126 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5127 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005128 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 return 0;
5130 }
5131
5132 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5133 "Updating global configuration to: " + values);
5134
5135 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5136 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5137 values.colorMode,
5138 values.densityDpi,
5139 values.fontScale,
5140 values.hardKeyboardHidden,
5141 values.keyboard,
5142 values.keyboardHidden,
5143 values.mcc,
5144 values.mnc,
5145 values.navigation,
5146 values.navigationHidden,
5147 values.orientation,
5148 values.screenHeightDp,
5149 values.screenLayout,
5150 values.screenWidthDp,
5151 values.smallestScreenWidthDp,
5152 values.touchscreen,
5153 values.uiMode);
5154
5155
5156 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5157 final LocaleList locales = values.getLocales();
5158 int bestLocaleIndex = 0;
5159 if (locales.size() > 1) {
5160 if (mSupportedSystemLocales == null) {
5161 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5162 }
5163 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5164 }
5165 SystemProperties.set("persist.sys.locale",
5166 locales.get(bestLocaleIndex).toLanguageTag());
5167 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005168
5169 final Message m = PooledLambda.obtainMessage(
5170 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5171 locales.get(bestLocaleIndex));
5172 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005173 }
5174
Yunfan Chen75157d72018-07-27 14:47:21 +09005175 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005176
5177 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005178 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005179
5180 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5181 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005182 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183
5184 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005185 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186
5187 AttributeCache ac = AttributeCache.instance();
5188 if (ac != null) {
5189 ac.updateConfiguration(mTempConfig);
5190 }
5191
5192 // Make sure all resources in our process are updated right now, so that anyone who is going
5193 // to retrieve resource values after we return will be sure to get the new ones. This is
5194 // especially important during boot, where the first config change needs to guarantee all
5195 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005196 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197
5198 // We need another copy of global config because we're scheduling some calls instead of
5199 // running them in place. We need to be sure that object we send will be handled unchanged.
5200 final Configuration configCopy = new Configuration(mTempConfig);
5201 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005202 final Message msg = PooledLambda.obtainMessage(
5203 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5204 this, userId, configCopy);
5205 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005206 }
5207
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005208 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5209 for (int i = pidMap.size() - 1; i >= 0; i--) {
5210 final int pid = pidMap.keyAt(i);
5211 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005212 if (DEBUG_CONFIGURATION) {
5213 Slog.v(TAG_CONFIGURATION, "Update process config of "
5214 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005216 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005217 }
5218
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005219 final Message msg = PooledLambda.obtainMessage(
5220 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5221 mAmInternal, changes, initLocale);
5222 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223
5224 // Override configuration of the default display duplicates global config, so we need to
5225 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005226 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5227 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228
5229 return changes;
5230 }
5231
Riddle Hsua0022cd2019-09-09 21:12:41 +08005232 /** @see WindowSurfacePlacer#deferLayout */
5233 void deferWindowLayout() {
5234 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5235 // Reset the reasons at the first entrance because we only care about the changes in the
5236 // deferred scope.
5237 mLayoutReasons = 0;
5238 }
5239
5240 mWindowManager.mWindowPlacerLocked.deferLayout();
5241 }
5242
5243 /** @see WindowSurfacePlacer#continueLayout */
5244 void continueWindowLayout() {
5245 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5246 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5247 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5248 }
5249 }
5250
5251 /**
5252 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5253 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5254 * defer count is gone.
5255 */
5256 void addWindowLayoutReasons(@LayoutReason int reasons) {
5257 mLayoutReasons |= reasons;
5258 }
5259
Wale Ogunwalef6733932018-06-27 05:14:34 -07005260 private void updateEventDispatchingLocked(boolean booted) {
5261 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5262 }
5263
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005264 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5265 final ContentResolver resolver = mContext.getContentResolver();
5266 Settings.System.putConfigurationForUser(resolver, config, userId);
5267 }
5268
5269 private void sendLocaleToMountDaemonMsg(Locale l) {
5270 try {
5271 IBinder service = ServiceManager.getService("mount");
5272 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5273 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5274 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5275 } catch (RemoteException e) {
5276 Log.e(TAG, "Error storing locale for decryption UI", e);
5277 }
5278 }
5279
Alison Cichowlas3e340502018-08-07 17:15:01 -04005280 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5281 mStartActivitySources.remove(permissionToken);
5282 mExpiredStartAsCallerTokens.add(permissionToken);
5283 }
5284
5285 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5286 mExpiredStartAsCallerTokens.remove(permissionToken);
5287 }
5288
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005289 boolean isActivityStartsLoggingEnabled() {
5290 return mAmInternal.isActivityStartsLoggingEnabled();
5291 }
5292
Michal Karpinski8596ded2018-11-14 14:43:48 +00005293 boolean isBackgroundActivityStartsEnabled() {
5294 return mAmInternal.isBackgroundActivityStartsEnabled();
5295 }
5296
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 void enableScreenAfterBoot(boolean booted) {
5298 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5299 SystemClock.uptimeMillis());
5300 mWindowManager.enableScreenAfterBoot();
5301
5302 synchronized (mGlobalLock) {
5303 updateEventDispatchingLocked(booted);
5304 }
5305 }
5306
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005307 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5308 if (r == null || !r.hasProcess()) {
5309 return KEY_DISPATCHING_TIMEOUT_MS;
5310 }
5311 return getInputDispatchingTimeoutLocked(r.app);
5312 }
5313
5314 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005315 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005316 }
5317
Wale Ogunwalef6733932018-06-27 05:14:34 -07005318 /**
5319 * Decide based on the configuration whether we should show the ANR,
5320 * crash, etc dialogs. The idea is that if there is no affordance to
5321 * press the on-screen buttons, or the user experience would be more
5322 * greatly impacted than the crash itself, we shouldn't show the dialog.
5323 *
5324 * A thought: SystemUI might also want to get told about this, the Power
5325 * dialog / global actions also might want different behaviors.
5326 */
5327 private void updateShouldShowDialogsLocked(Configuration config) {
5328 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5329 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5330 && config.navigation == Configuration.NAVIGATION_NONAV);
5331 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5332 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5333 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5334 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5335 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5336 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5337 HIDE_ERROR_DIALOGS, 0) != 0;
5338 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5339 }
5340
5341 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5342 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5343 FONT_SCALE, 1.0f, userId);
5344
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005345 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005346 if (getGlobalConfiguration().fontScale == scaleFactor) {
5347 return;
5348 }
5349
5350 final Configuration configuration
5351 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5352 configuration.fontScale = scaleFactor;
5353 updatePersistentConfiguration(configuration, userId);
5354 }
5355 }
5356
5357 // Actually is sleeping or shutting down or whatever else in the future
5358 // is an inactive state.
5359 boolean isSleepingOrShuttingDownLocked() {
5360 return isSleepingLocked() || mShuttingDown;
5361 }
5362
5363 boolean isSleepingLocked() {
5364 return mSleeping;
5365 }
5366
Riddle Hsu16567132018-08-16 21:37:47 +08005367 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005368 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005369 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005370 if (task.isActivityTypeStandard()) {
5371 if (mCurAppTimeTracker != r.appTimeTracker) {
5372 // We are switching app tracking. Complete the current one.
5373 if (mCurAppTimeTracker != null) {
5374 mCurAppTimeTracker.stop();
5375 mH.obtainMessage(
5376 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005377 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 mCurAppTimeTracker = null;
5379 }
5380 if (r.appTimeTracker != null) {
5381 mCurAppTimeTracker = r.appTimeTracker;
5382 startTimeTrackingFocusedActivityLocked();
5383 }
5384 } else {
5385 startTimeTrackingFocusedActivityLocked();
5386 }
5387 } else {
5388 r.appTimeTracker = null;
5389 }
5390 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5391 // TODO: Probably not, because we don't want to resume voice on switching
5392 // back to this activity
5393 if (task.voiceInteractor != null) {
5394 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5395 } else {
5396 finishRunningVoiceLocked();
5397
5398 if (mLastResumedActivity != null) {
5399 final IVoiceInteractionSession session;
5400
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005401 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005402 if (lastResumedActivityTask != null
5403 && lastResumedActivityTask.voiceSession != null) {
5404 session = lastResumedActivityTask.voiceSession;
5405 } else {
5406 session = mLastResumedActivity.voiceSession;
5407 }
5408
5409 if (session != null) {
5410 // We had been in a voice interaction session, but now focused has
5411 // move to something different. Just finish the session, we can't
5412 // return to it and retain the proper state and synchronization with
5413 // the voice interaction service.
5414 finishVoiceTask(session);
5415 }
5416 }
5417 }
5418
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005419 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5420 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005421 }
5422 updateResumedAppTrace(r);
5423 mLastResumedActivity = r;
5424
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005425 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005426
5427 applyUpdateLockStateLocked(r);
5428 applyUpdateVrModeLocked(r);
5429
5430 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005431 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 r == null ? "NULL" : r.shortComponentName,
5433 reason);
5434 }
5435
5436 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5437 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005438 final ActivityTaskManagerInternal.SleepToken token =
5439 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 updateSleepIfNeededLocked();
5441 return token;
5442 }
5443 }
5444
5445 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005446 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005447 final boolean wasSleeping = mSleeping;
5448 boolean updateOomAdj = false;
5449
5450 if (!shouldSleep) {
5451 // If wasSleeping is true, we need to wake up activity manager state from when
5452 // we started sleeping. In either case, we need to apply the sleep tokens, which
5453 // will wake up stacks or put them to sleep as appropriate.
5454 if (wasSleeping) {
5455 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005456 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5457 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 startTimeTrackingFocusedActivityLocked();
5459 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005460 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5462 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005463 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005464 if (wasSleeping) {
5465 updateOomAdj = true;
5466 }
5467 } else if (!mSleeping && shouldSleep) {
5468 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005469 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5470 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005471 if (mCurAppTimeTracker != null) {
5472 mCurAppTimeTracker.stop();
5473 }
5474 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005475 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005476 mStackSupervisor.goingToSleepLocked();
5477 updateResumedAppTrace(null /* resumed */);
5478 updateOomAdj = true;
5479 }
5480 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005481 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005482 }
5483 }
5484
5485 void updateOomAdj() {
5486 mH.post(mAmInternal::updateOomAdj);
5487 }
5488
Wale Ogunwale53783742018-09-16 10:21:51 -07005489 void updateCpuStats() {
5490 mH.post(mAmInternal::updateCpuStats);
5491 }
5492
Hui Yu03d12402018-12-06 18:00:37 -08005493 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5494 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005495 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5496 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005497 mH.sendMessage(m);
5498 }
5499
Hui Yu03d12402018-12-06 18:00:37 -08005500 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005501 ComponentName taskRoot = null;
5502 final TaskRecord task = activity.getTaskRecord();
5503 if (task != null) {
5504 final ActivityRecord rootActivity = task.getRootActivity();
5505 if (rootActivity != null) {
5506 taskRoot = rootActivity.mActivityComponent;
5507 }
5508 }
5509
Hui Yu03d12402018-12-06 18:00:37 -08005510 final Message m = PooledLambda.obtainMessage(
5511 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005512 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005513 mH.sendMessage(m);
5514 }
5515
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005516 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5517 String hostingType) {
5518 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005519 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5520 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005521 + activity.processName);
5522 }
5523 // Post message to start process to avoid possible deadlock of calling into AMS with the
5524 // ATMS lock held.
5525 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5526 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5527 isTop, hostingType, activity.intent.getComponent());
5528 mH.sendMessage(m);
5529 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005530 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005531 }
5532 }
5533
Wale Ogunwale53783742018-09-16 10:21:51 -07005534 void setBooting(boolean booting) {
5535 mAmInternal.setBooting(booting);
5536 }
5537
5538 boolean isBooting() {
5539 return mAmInternal.isBooting();
5540 }
5541
5542 void setBooted(boolean booted) {
5543 mAmInternal.setBooted(booted);
5544 }
5545
5546 boolean isBooted() {
5547 return mAmInternal.isBooted();
5548 }
5549
5550 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5551 mH.post(() -> {
5552 if (finishBooting) {
5553 mAmInternal.finishBooting();
5554 }
5555 if (enableScreen) {
5556 mInternal.enableScreenAfterBoot(isBooted());
5557 }
5558 });
5559 }
5560
5561 void setHeavyWeightProcess(ActivityRecord root) {
5562 mHeavyWeightProcess = root.app;
5563 final Message m = PooledLambda.obtainMessage(
5564 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005565 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005566 mH.sendMessage(m);
5567 }
5568
5569 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5570 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5571 return;
5572 }
5573
5574 mHeavyWeightProcess = null;
5575 final Message m = PooledLambda.obtainMessage(
5576 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5577 proc.mUserId);
5578 mH.sendMessage(m);
5579 }
5580
5581 private void cancelHeavyWeightProcessNotification(int userId) {
5582 final INotificationManager inm = NotificationManager.getService();
5583 if (inm == null) {
5584 return;
5585 }
5586 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005587 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005588 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5589 } catch (RuntimeException e) {
5590 Slog.w(TAG, "Error canceling notification for service", e);
5591 } catch (RemoteException e) {
5592 }
5593
5594 }
5595
5596 private void postHeavyWeightProcessNotification(
5597 WindowProcessController proc, Intent intent, int userId) {
5598 if (proc == null) {
5599 return;
5600 }
5601
5602 final INotificationManager inm = NotificationManager.getService();
5603 if (inm == null) {
5604 return;
5605 }
5606
5607 try {
5608 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5609 String text = mContext.getString(R.string.heavy_weight_notification,
5610 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5611 Notification notification =
5612 new Notification.Builder(context,
5613 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5614 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5615 .setWhen(0)
5616 .setOngoing(true)
5617 .setTicker(text)
5618 .setColor(mContext.getColor(
5619 com.android.internal.R.color.system_notification_accent_color))
5620 .setContentTitle(text)
5621 .setContentText(
5622 mContext.getText(R.string.heavy_weight_notification_detail))
5623 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5624 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5625 new UserHandle(userId)))
5626 .build();
5627 try {
5628 inm.enqueueNotificationWithTag("android", "android", null,
5629 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5630 } catch (RuntimeException e) {
5631 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5632 } catch (RemoteException e) {
5633 }
5634 } catch (PackageManager.NameNotFoundException e) {
5635 Slog.w(TAG, "Unable to create context for heavy notification", e);
5636 }
5637
5638 }
5639
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005640 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5641 IBinder token, String resultWho, int requestCode, Intent[] intents,
5642 String[] resolvedTypes, int flags, Bundle bOptions) {
5643
5644 ActivityRecord activity = null;
5645 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5646 activity = ActivityRecord.isInStackLocked(token);
5647 if (activity == null) {
5648 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5649 return null;
5650 }
5651 if (activity.finishing) {
5652 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5653 return null;
5654 }
5655 }
5656
5657 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5658 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5659 bOptions);
5660 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5661 if (noCreate) {
5662 return rec;
5663 }
5664 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5665 if (activity.pendingResults == null) {
5666 activity.pendingResults = new HashSet<>();
5667 }
5668 activity.pendingResults.add(rec.ref);
5669 }
5670 return rec;
5671 }
5672
Andrii Kulian52d255c2018-07-13 11:32:19 -07005673 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005674 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005675 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005676 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5677 mCurAppTimeTracker.start(resumedActivity.packageName);
5678 }
5679 }
5680
5681 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5682 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005683 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005684 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5685 }
5686 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005687 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005688 constructResumedTraceName(resumed.packageName), 0);
5689 }
5690 mTracedResumedActivity = resumed;
5691 }
5692
5693 private String constructResumedTraceName(String packageName) {
5694 return "focused app: " + packageName;
5695 }
5696
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005697 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005698 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005699 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005700 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005701 // mainStack is null during startup.
5702 if (mainStack != null) {
5703 if (changes != 0 && starting == null) {
5704 // If the configuration changed, and the caller is not already
5705 // in the process of starting an activity, then find the top
5706 // activity to check if its configuration needs to change.
5707 starting = mainStack.topRunningActivityLocked();
5708 }
5709
5710 if (starting != null) {
5711 kept = starting.ensureActivityConfiguration(changes,
5712 false /* preserveWindow */);
5713 // And we need to make sure at this point that all other activities
5714 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005715 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005716 !PRESERVE_WINDOWS);
5717 }
5718 }
5719
5720 return kept;
5721 }
5722
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005723 void scheduleAppGcsLocked() {
5724 mH.post(() -> mAmInternal.scheduleAppGcs());
5725 }
5726
Wale Ogunwale53783742018-09-16 10:21:51 -07005727 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5728 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5729 }
5730
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005731 /**
5732 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5733 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5734 * on demand.
5735 */
5736 IPackageManager getPackageManager() {
5737 return AppGlobals.getPackageManager();
5738 }
5739
5740 PackageManagerInternal getPackageManagerInternalLocked() {
5741 if (mPmInternal == null) {
5742 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5743 }
5744 return mPmInternal;
5745 }
5746
Hai Zhangf4da9be2019-05-01 13:46:06 +08005747 PermissionPolicyInternal getPermissionPolicyInternal() {
5748 if (mPermissionPolicyInternal == null) {
5749 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5750 }
5751 return mPermissionPolicyInternal;
5752 }
5753
Wale Ogunwale008163e2018-07-23 23:11:08 -07005754 AppWarnings getAppWarningsLocked() {
5755 return mAppWarnings;
5756 }
5757
Wale Ogunwale214f3482018-10-04 11:00:47 -07005758 Intent getHomeIntent() {
5759 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5760 intent.setComponent(mTopComponent);
5761 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5762 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5763 intent.addCategory(Intent.CATEGORY_HOME);
5764 }
5765 return intent;
5766 }
5767
Chilun2ef71f72018-11-16 17:57:15 +08005768 /**
5769 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5770 * activities.
5771 *
5772 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5773 * component defined in config_secondaryHomeComponent.
5774 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5775 */
5776 Intent getSecondaryHomeIntent(String preferredPackage) {
5777 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005778 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5779 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5780 if (preferredPackage == null || useSystemProvidedLauncher) {
5781 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005782 final String secondaryHomeComponent = mContext.getResources().getString(
5783 com.android.internal.R.string.config_secondaryHomeComponent);
5784 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5785 } else {
5786 intent.setPackage(preferredPackage);
5787 }
5788 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5789 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5790 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5791 }
5792 return intent;
5793 }
5794
Wale Ogunwale214f3482018-10-04 11:00:47 -07005795 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5796 if (info == null) return null;
5797 ApplicationInfo newInfo = new ApplicationInfo(info);
5798 newInfo.initForUser(userId);
5799 return newInfo;
5800 }
5801
Wale Ogunwale9c103022018-10-18 07:44:54 -07005802 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005803 if (uid == SYSTEM_UID) {
5804 // The system gets to run in any process. If there are multiple processes with the same
5805 // uid, just pick the first (this should never happen).
5806 final SparseArray<WindowProcessController> procs =
5807 mProcessNames.getMap().get(processName);
5808 if (procs == null) return null;
5809 final int procCount = procs.size();
5810 for (int i = 0; i < procCount; i++) {
5811 final int procUid = procs.keyAt(i);
5812 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5813 // Don't use an app process or different user process for system component.
5814 continue;
5815 }
5816 return procs.valueAt(i);
5817 }
5818 }
5819
5820 return mProcessNames.get(processName, uid);
5821 }
5822
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005823 WindowProcessController getProcessController(IApplicationThread thread) {
5824 if (thread == null) {
5825 return null;
5826 }
5827
5828 final IBinder threadBinder = thread.asBinder();
5829 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5830 for (int i = pmap.size()-1; i >= 0; i--) {
5831 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5832 for (int j = procs.size() - 1; j >= 0; j--) {
5833 final WindowProcessController proc = procs.valueAt(j);
5834 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5835 return proc;
5836 }
5837 }
5838 }
5839
5840 return null;
5841 }
5842
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005843 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005844 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005845 if (proc == null) return null;
5846 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5847 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005848 }
5849 return null;
5850 }
5851
Riddle Hsua0536432019-02-16 00:38:59 +08005852 int getUidState(int uid) {
5853 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005854 }
5855
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005856 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005857 // A uid is considered to be foreground if it has a visible non-toast window.
5858 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005859 }
5860
Ricky Wai96f5c352019-04-10 18:40:17 +01005861 boolean isDeviceOwner(int uid) {
5862 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005863 }
5864
Ricky Wai96f5c352019-04-10 18:40:17 +01005865 void setDeviceOwnerUid(int uid) {
5866 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005867 }
5868
Wale Ogunwale9de19442018-10-18 19:05:03 -07005869 /**
5870 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5871 * the whitelist
5872 */
5873 String getPendingTempWhitelistTagForUidLocked(int uid) {
5874 return mPendingTempWhitelist.get(uid);
5875 }
5876
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005877 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5878 if (true || Build.IS_USER) {
5879 return;
5880 }
5881
5882 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5883 StrictMode.allowThreadDiskWrites();
5884 try {
5885 File tracesDir = new File("/data/anr");
5886 File tracesFile = null;
5887 try {
5888 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5889
5890 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005891 String timeString =
5892 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5893 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005894 sb.append(": ");
5895 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5896 sb.append(" since ");
5897 sb.append(msg);
5898 FileOutputStream fos = new FileOutputStream(tracesFile);
5899 fos.write(sb.toString().getBytes());
5900 if (app == null) {
5901 fos.write("\n*** No application process!".getBytes());
5902 }
5903 fos.close();
5904 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5905 } catch (IOException e) {
5906 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5907 return;
5908 }
5909
5910 if (app != null && app.getPid() > 0) {
5911 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5912 firstPids.add(app.getPid());
5913 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5914 }
5915
5916 File lastTracesFile = null;
5917 File curTracesFile = null;
5918 for (int i=9; i>=0; i--) {
5919 String name = String.format(Locale.US, "slow%02d.txt", i);
5920 curTracesFile = new File(tracesDir, name);
5921 if (curTracesFile.exists()) {
5922 if (lastTracesFile != null) {
5923 curTracesFile.renameTo(lastTracesFile);
5924 } else {
5925 curTracesFile.delete();
5926 }
5927 }
5928 lastTracesFile = curTracesFile;
5929 }
5930 tracesFile.renameTo(curTracesFile);
5931 } finally {
5932 StrictMode.setThreadPolicy(oldPolicy);
5933 }
5934 }
5935
Michal Karpinskida34cd42019-04-02 19:46:52 +01005936 boolean isAssociatedCompanionApp(int userId, int uid) {
5937 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5938 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005939 return false;
5940 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005941 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005942 }
5943
Issei Suzuki734bc942019-06-05 13:59:52 +02005944 void notifySingleTaskDisplayEmpty(int displayId) {
5945 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5946 }
5947
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005948 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005949 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005950
5951
Wale Ogunwale98875612018-10-12 07:53:02 -07005952 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5953 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005954
Riddle Hsud93a6c42018-11-29 21:50:06 +08005955 H(Looper looper) {
5956 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005957 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005958
5959 @Override
5960 public void handleMessage(Message msg) {
5961 switch (msg.what) {
5962 case REPORT_TIME_TRACKER_MSG: {
5963 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5964 tracker.deliverResult(mContext);
5965 } break;
5966 }
5967 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005968 }
5969
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005970 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005971 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005972
5973 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005974 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005975 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005976
5977 @Override
5978 public void handleMessage(Message msg) {
5979 switch (msg.what) {
5980 case DISMISS_DIALOG_UI_MSG: {
5981 final Dialog d = (Dialog) msg.obj;
5982 d.dismiss();
5983 break;
5984 }
5985 }
5986 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005987 }
5988
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005989 final class LocalService extends ActivityTaskManagerInternal {
5990 @Override
5991 public SleepToken acquireSleepToken(String tag, int displayId) {
5992 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005993 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005994 }
5995
5996 @Override
5997 public ComponentName getHomeActivityForUser(int userId) {
5998 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005999 final ActivityRecord homeActivity =
6000 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006001 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006002 }
6003 }
6004
6005 @Override
6006 public void onLocalVoiceInteractionStarted(IBinder activity,
6007 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6008 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006009 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006010 }
6011 }
6012
6013 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006014 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006015 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006016 synchronized (mGlobalLock) {
6017 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006018 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006019 }
6020 }
6021
6022 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006023 public void notifySingleTaskDisplayDrawn(int displayId) {
6024 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6025 }
6026
6027 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006028 public void notifyAppTransitionFinished() {
6029 synchronized (mGlobalLock) {
6030 mStackSupervisor.notifyAppTransitionDone();
6031 }
6032 }
6033
6034 @Override
6035 public void notifyAppTransitionCancelled() {
6036 synchronized (mGlobalLock) {
6037 mStackSupervisor.notifyAppTransitionDone();
6038 }
6039 }
6040
6041 @Override
6042 public List<IBinder> getTopVisibleActivities() {
6043 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006044 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006045 }
6046 }
6047
6048 @Override
6049 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6050 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006051 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006052 }
6053 }
6054
6055 @Override
6056 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6057 Bundle bOptions) {
6058 Preconditions.checkNotNull(intents, "intents");
6059 final String[] resolvedTypes = new String[intents.length];
6060
6061 // UID of the package on user userId.
6062 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6063 // packageUid may not be initialized.
6064 int packageUid = 0;
6065 final long ident = Binder.clearCallingIdentity();
6066
6067 try {
6068 for (int i = 0; i < intents.length; i++) {
6069 resolvedTypes[i] =
6070 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6071 }
6072
6073 packageUid = AppGlobals.getPackageManager().getPackageUid(
6074 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6075 } catch (RemoteException e) {
6076 // Shouldn't happen.
6077 } finally {
6078 Binder.restoreCallingIdentity(ident);
6079 }
6080
Riddle Hsu591bf612019-02-14 17:55:31 +08006081 return getActivityStartController().startActivitiesInPackage(
6082 packageUid, packageName,
6083 intents, resolvedTypes, null /* resultTo */,
6084 SafeActivityOptions.fromBundle(bOptions), userId,
6085 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6086 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006087 }
6088
6089 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006090 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6091 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6092 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6093 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006094 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006095 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006096 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6097 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6098 userId, validateIncomingUser, originatingPendingIntent,
6099 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006100 }
6101 }
6102
6103 @Override
6104 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6105 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6106 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6107 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006108 PendingIntentRecord originatingPendingIntent,
6109 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006110 synchronized (mGlobalLock) {
6111 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6112 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6113 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006114 validateIncomingUser, originatingPendingIntent,
6115 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006116 }
6117 }
6118
6119 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006120 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6121 Intent intent, Bundle options, int userId) {
6122 return ActivityTaskManagerService.this.startActivityAsUser(
6123 caller, callerPacakge, intent,
6124 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6125 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6126 false /*validateIncomingUser*/);
6127 }
6128
6129 @Override
lumark588a3e82018-07-20 18:53:54 +08006130 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 synchronized (mGlobalLock) {
6132
6133 // We might change the visibilities here, so prepare an empty app transition which
6134 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006135 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006136 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006137 if (activityDisplay == null) {
6138 return;
6139 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006140 final DisplayContent dc = activityDisplay.mDisplayContent;
6141 final boolean wasTransitionSet =
6142 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006143 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006144 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006146 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006147
6148 // If there was a transition set already we don't want to interfere with it as we
6149 // might be starting it too early.
6150 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006151 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006152 }
6153 }
6154 if (callback != null) {
6155 callback.run();
6156 }
6157 }
6158
6159 @Override
6160 public void notifyKeyguardTrustedChanged() {
6161 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006162 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006163 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 }
6165 }
6166 }
6167
6168 /**
6169 * Called after virtual display Id is updated by
6170 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6171 * {@param vrVr2dDisplayId}.
6172 */
6173 @Override
6174 public void setVr2dDisplayId(int vr2dDisplayId) {
6175 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6176 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006177 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179 }
6180
6181 @Override
6182 public void setFocusedActivity(IBinder token) {
6183 synchronized (mGlobalLock) {
6184 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6185 if (r == null) {
6186 throw new IllegalArgumentException(
6187 "setFocusedActivity: No activity record matching token=" + token);
6188 }
Louis Chang19443452018-10-09 12:10:21 +08006189 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006190 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 }
6192 }
6193 }
6194
6195 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006196 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006197 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198 }
6199
6200 @Override
6201 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006202 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006203 }
6204
6205 @Override
6206 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006207 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 }
6209
6210 @Override
6211 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6212 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6213 }
6214
6215 @Override
6216 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006217 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006219
6220 @Override
6221 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6222 synchronized (mGlobalLock) {
6223 mActiveVoiceInteractionServiceComponent = component;
6224 }
6225 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006226
6227 @Override
6228 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6229 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6230 return;
6231 }
6232 synchronized (mGlobalLock) {
6233 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6234 if (types == null) {
6235 if (uid < 0) {
6236 return;
6237 }
6238 types = new ArrayMap<>();
6239 mAllowAppSwitchUids.put(userId, types);
6240 }
6241 if (uid < 0) {
6242 types.remove(type);
6243 } else {
6244 types.put(type, uid);
6245 }
6246 }
6247 }
6248
6249 @Override
6250 public void onUserStopped(int userId) {
6251 synchronized (mGlobalLock) {
6252 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6253 mAllowAppSwitchUids.remove(userId);
6254 }
6255 }
6256
6257 @Override
6258 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6259 synchronized (mGlobalLock) {
6260 return ActivityTaskManagerService.this.isGetTasksAllowed(
6261 caller, callingPid, callingUid);
6262 }
6263 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006264
Riddle Hsua0536432019-02-16 00:38:59 +08006265 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006266 @Override
6267 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006268 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006269 mProcessNames.put(proc.mName, proc.mUid, proc);
6270 }
6271 }
6272
Riddle Hsua0536432019-02-16 00:38:59 +08006273 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006274 @Override
6275 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006276 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006277 mProcessNames.remove(name, uid);
6278 }
6279 }
6280
Riddle Hsua0536432019-02-16 00:38:59 +08006281 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006282 @Override
6283 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006284 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006285 if (proc == mHomeProcess) {
6286 mHomeProcess = null;
6287 }
6288 if (proc == mPreviousProcess) {
6289 mPreviousProcess = null;
6290 }
6291 }
6292 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006293
Riddle Hsua0536432019-02-16 00:38:59 +08006294 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006295 @Override
6296 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006297 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006298 return mTopProcessState;
6299 }
6300 }
6301
Riddle Hsua0536432019-02-16 00:38:59 +08006302 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006303 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006304 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006305 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006306 return proc == mHeavyWeightProcess;
6307 }
6308 }
6309
Riddle Hsua0536432019-02-16 00:38:59 +08006310 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006311 @Override
6312 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006313 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6315 }
6316 }
6317
6318 @Override
6319 public void finishHeavyWeightApp() {
6320 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006321 if (mHeavyWeightProcess != null) {
6322 mHeavyWeightProcess.finishActivities();
6323 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006324 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6325 mHeavyWeightProcess);
6326 }
6327 }
6328
Riddle Hsua0536432019-02-16 00:38:59 +08006329 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006330 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006331 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006332 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006333 return isSleepingLocked();
6334 }
6335 }
6336
6337 @Override
6338 public boolean isShuttingDown() {
6339 synchronized (mGlobalLock) {
6340 return mShuttingDown;
6341 }
6342 }
6343
6344 @Override
6345 public boolean shuttingDown(boolean booted, int timeout) {
6346 synchronized (mGlobalLock) {
6347 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006348 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006349 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006350 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006351 return mStackSupervisor.shutdownLocked(timeout);
6352 }
6353 }
6354
6355 @Override
6356 public void enableScreenAfterBoot(boolean booted) {
6357 synchronized (mGlobalLock) {
6358 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6359 SystemClock.uptimeMillis());
6360 mWindowManager.enableScreenAfterBoot();
6361 updateEventDispatchingLocked(booted);
6362 }
6363 }
6364
6365 @Override
6366 public boolean showStrictModeViolationDialog() {
6367 synchronized (mGlobalLock) {
6368 return mShowDialogs && !mSleeping && !mShuttingDown;
6369 }
6370 }
6371
6372 @Override
6373 public void showSystemReadyErrorDialogsIfNeeded() {
6374 synchronized (mGlobalLock) {
6375 try {
6376 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6377 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6378 + " data partition or your device will be unstable.");
6379 mUiHandler.post(() -> {
6380 if (mShowDialogs) {
6381 AlertDialog d = new BaseErrorDialog(mUiContext);
6382 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6383 d.setCancelable(false);
6384 d.setTitle(mUiContext.getText(R.string.android_system_label));
6385 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6386 d.setButton(DialogInterface.BUTTON_POSITIVE,
6387 mUiContext.getText(R.string.ok),
6388 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6389 d.show();
6390 }
6391 });
6392 }
6393 } catch (RemoteException e) {
6394 }
6395
6396 if (!Build.isBuildConsistent()) {
6397 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6398 mUiHandler.post(() -> {
6399 if (mShowDialogs) {
6400 AlertDialog d = new BaseErrorDialog(mUiContext);
6401 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6402 d.setCancelable(false);
6403 d.setTitle(mUiContext.getText(R.string.android_system_label));
6404 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6405 d.setButton(DialogInterface.BUTTON_POSITIVE,
6406 mUiContext.getText(R.string.ok),
6407 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6408 d.show();
6409 }
6410 });
6411 }
6412 }
6413 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006414
6415 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006416 public void onProcessMapped(int pid, WindowProcessController proc) {
6417 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006418 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006419 }
6420 }
6421
6422 @Override
6423 public void onProcessUnMapped(int pid) {
6424 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006425 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006426 }
6427 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006428
6429 @Override
6430 public void onPackageDataCleared(String name) {
6431 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006432 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006433 mAppWarnings.onPackageDataCleared(name);
6434 }
6435 }
6436
6437 @Override
6438 public void onPackageUninstalled(String name) {
6439 synchronized (mGlobalLock) {
6440 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006442 }
6443 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006444
6445 @Override
6446 public void onPackageAdded(String name, boolean replacing) {
6447 synchronized (mGlobalLock) {
6448 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6449 }
6450 }
6451
6452 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006453 public void onPackageReplaced(ApplicationInfo aInfo) {
6454 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006455 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006456 }
6457 }
6458
6459 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006460 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6461 synchronized (mGlobalLock) {
6462 return compatibilityInfoForPackageLocked(ai);
6463 }
6464 }
6465
Yunfan Chen75157d72018-07-27 14:47:21 +09006466 /**
6467 * Set the corresponding display information for the process global configuration. To be
6468 * called when we need to show IME on a different display.
6469 *
6470 * @param pid The process id associated with the IME window.
6471 * @param displayId The ID of the display showing the IME.
6472 */
6473 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006474 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006475 // Don't update process-level configuration for Multi-Client IME process since other
6476 // IMEs on other displays will also receive this configuration change due to IME
6477 // services use the same application config/context.
6478 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006479
Yunfan Chen75157d72018-07-27 14:47:21 +09006480 if (pid == MY_PID || pid < 0) {
6481 if (DEBUG_CONFIGURATION) {
6482 Slog.w(TAG,
6483 "Trying to update display configuration for system/invalid process.");
6484 }
6485 return;
6486 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006487 synchronized (mGlobalLock) {
6488 final ActivityDisplay activityDisplay =
6489 mRootActivityContainer.getActivityDisplay(displayId);
6490 if (activityDisplay == null) {
6491 // Call might come when display is not yet added or has been removed.
6492 if (DEBUG_CONFIGURATION) {
6493 Slog.w(TAG, "Trying to update display configuration for non-existing "
6494 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006495 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006496 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006497 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006498 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006499 if (process == null) {
6500 if (DEBUG_CONFIGURATION) {
6501 Slog.w(TAG, "Trying to update display configuration for invalid "
6502 + "process, pid=" + pid);
6503 }
6504 return;
6505 }
lumarkddc77fb2019-06-27 22:22:23 +08006506 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006507 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6508 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006509 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006510
6511 @Override
6512 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006513 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006514 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006515 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6516 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006517 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006518 }
6519 }
6520 }
6521
6522 @Override
6523 public void clearPendingResultForActivity(IBinder activityToken,
6524 WeakReference<PendingIntentRecord> pir) {
6525 synchronized (mGlobalLock) {
6526 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6527 if (r != null && r.pendingResults != null) {
6528 r.pendingResults.remove(pir);
6529 }
6530 }
6531 }
6532
6533 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006534 public ActivityTokens getTopActivityForTask(int taskId) {
6535 synchronized (mGlobalLock) {
6536 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6537 if (taskRecord == null) {
6538 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6539 + " Requested task not found");
6540 return null;
6541 }
6542 final ActivityRecord activity = taskRecord.getTopActivity();
6543 if (activity == null) {
6544 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6545 + " Requested activity not found");
6546 return null;
6547 }
6548 if (!activity.attachedToProcess()) {
6549 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6550 + activity);
6551 return null;
6552 }
6553 return new ActivityTokens(activity.appToken, activity.assistToken,
6554 activity.app.getThread());
6555 }
6556 }
6557
6558 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006559 public IIntentSender getIntentSender(int type, String packageName,
6560 int callingUid, int userId, IBinder token, String resultWho,
6561 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6562 Bundle bOptions) {
6563 synchronized (mGlobalLock) {
6564 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6565 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6566 }
6567 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006568
6569 @Override
6570 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6571 synchronized (mGlobalLock) {
6572 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6573 if (r == null) {
6574 return null;
6575 }
6576 if (r.mServiceConnectionsHolder == null) {
6577 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6578 ActivityTaskManagerService.this, r);
6579 }
6580
6581 return r.mServiceConnectionsHolder;
6582 }
6583 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006584
6585 @Override
6586 public Intent getHomeIntent() {
6587 synchronized (mGlobalLock) {
6588 return ActivityTaskManagerService.this.getHomeIntent();
6589 }
6590 }
6591
6592 @Override
6593 public boolean startHomeActivity(int userId, String reason) {
6594 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006595 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006596 }
6597 }
6598
6599 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006600 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006601 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006602 synchronized (mGlobalLock) {
6603 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006604 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006605 }
Chilun8b1f1be2019-03-13 17:14:36 +08006606 }
6607
6608 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006609 public boolean startHomeOnAllDisplays(int userId, String reason) {
6610 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006611 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006612 }
6613 }
6614
Riddle Hsua0536432019-02-16 00:38:59 +08006615 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006616 @Override
6617 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006618 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006619 if (mFactoryTest == FACTORY_TEST_OFF) {
6620 return false;
6621 }
6622 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6623 && wpc.mName.equals(mTopComponent.getPackageName())) {
6624 return true;
6625 }
6626 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6627 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6628 }
6629 }
6630
6631 @Override
6632 public void updateTopComponentForFactoryTest() {
6633 synchronized (mGlobalLock) {
6634 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6635 return;
6636 }
6637 final ResolveInfo ri = mContext.getPackageManager()
6638 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6639 final CharSequence errorMsg;
6640 if (ri != null) {
6641 final ActivityInfo ai = ri.activityInfo;
6642 final ApplicationInfo app = ai.applicationInfo;
6643 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6644 mTopAction = Intent.ACTION_FACTORY_TEST;
6645 mTopData = null;
6646 mTopComponent = new ComponentName(app.packageName, ai.name);
6647 errorMsg = null;
6648 } else {
6649 errorMsg = mContext.getResources().getText(
6650 com.android.internal.R.string.factorytest_not_system);
6651 }
6652 } else {
6653 errorMsg = mContext.getResources().getText(
6654 com.android.internal.R.string.factorytest_no_action);
6655 }
6656 if (errorMsg == null) {
6657 return;
6658 }
6659
6660 mTopAction = null;
6661 mTopData = null;
6662 mTopComponent = null;
6663 mUiHandler.post(() -> {
6664 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6665 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006666 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006667 });
6668 }
6669 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006670
Riddle Hsua0536432019-02-16 00:38:59 +08006671 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006672 @Override
6673 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6674 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006675 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006676 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006677 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006678
6679 wpc.clearRecentTasks();
6680 wpc.clearActivities();
6681
6682 if (wpc.isInstrumenting()) {
6683 finishInstrumentationCallback.run();
6684 }
6685
Jorim Jaggid0752812018-10-16 16:07:20 +02006686 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006687 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006688 try {
6689 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6690 // If there was nothing to resume, and we are not already restarting
6691 // this process, but there is a visible activity that is hosted by the
6692 // process...then make sure all visible activities are running, taking
6693 // care of restarting this process.
6694 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6695 !PRESERVE_WINDOWS);
6696 }
6697 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006698 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006700 }
6701 }
6702 }
6703
6704 @Override
6705 public void closeSystemDialogs(String reason) {
6706 enforceNotIsolatedCaller("closeSystemDialogs");
6707
6708 final int pid = Binder.getCallingPid();
6709 final int uid = Binder.getCallingUid();
6710 final long origId = Binder.clearCallingIdentity();
6711 try {
6712 synchronized (mGlobalLock) {
6713 // Only allow this from foreground processes, so that background
6714 // applications can't abuse it to prevent system UI from being shown.
6715 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006716 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006717 if (!proc.isPerceptible()) {
6718 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6719 + " from background process " + proc);
6720 return;
6721 }
6722 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006723 mWindowManager.closeSystemDialogs(reason);
6724
Wale Ogunwaled32da472018-11-16 07:19:28 -08006725 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006726 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006727 // Call into AM outside the synchronized block.
6728 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729 } finally {
6730 Binder.restoreCallingIdentity(origId);
6731 }
6732 }
6733
6734 @Override
6735 public void cleanupDisabledPackageComponents(
6736 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6737 synchronized (mGlobalLock) {
6738 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006739 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006740 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006741 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742 mStackSupervisor.scheduleIdleLocked();
6743 }
6744
6745 // Clean-up disabled tasks
6746 getRecentTasks().cleanupDisabledPackageTasksLocked(
6747 packageName, disabledClasses, userId);
6748 }
6749 }
6750
6751 @Override
6752 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6753 int userId) {
6754 synchronized (mGlobalLock) {
6755
6756 boolean didSomething =
6757 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006758 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 null, doit, evenPersistent, userId);
6760 return didSomething;
6761 }
6762 }
6763
6764 @Override
6765 public void resumeTopActivities(boolean scheduleIdle) {
6766 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006767 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 if (scheduleIdle) {
6769 mStackSupervisor.scheduleIdleLocked();
6770 }
6771 }
6772 }
6773
Riddle Hsua0536432019-02-16 00:38:59 +08006774 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006775 @Override
6776 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006777 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6779 }
6780 }
6781
Riddle Hsua0536432019-02-16 00:38:59 +08006782 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 @Override
6784 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006785 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006786 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6787 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6788 }
6789 try {
6790 return mRootActivityContainer.attachApplication(wpc);
6791 } finally {
6792 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6793 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006794 }
6795 }
6796
6797 @Override
6798 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6799 try {
6800 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6801 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6802 }
6803 } catch (RemoteException ex) {
6804 throw new SecurityException("Fail to check is caller a privileged app", ex);
6805 }
6806
6807 synchronized (mGlobalLock) {
6808 final long ident = Binder.clearCallingIdentity();
6809 try {
6810 if (mAmInternal.shouldConfirmCredentials(userId)) {
6811 if (mKeyguardController.isKeyguardLocked()) {
6812 // Showing launcher to avoid user entering credential twice.
6813 startHomeActivity(currentUserId, "notifyLockedProfile");
6814 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006815 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 }
6817 } finally {
6818 Binder.restoreCallingIdentity(ident);
6819 }
6820 }
6821 }
6822
6823 @Override
6824 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6825 mAmInternal.enforceCallingPermission(
6826 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6827
6828 synchronized (mGlobalLock) {
6829 final long ident = Binder.clearCallingIdentity();
6830 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006831 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6832 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6835 UserHandle.CURRENT);
6836 } finally {
6837 Binder.restoreCallingIdentity(ident);
6838 }
6839 }
6840 }
6841
6842 @Override
6843 public void writeActivitiesToProto(ProtoOutputStream proto) {
6844 synchronized (mGlobalLock) {
6845 // The output proto of "activity --proto activities"
6846 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006847 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006848 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6849 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006850 }
6851 }
6852
6853 @Override
6854 public void saveANRState(String reason) {
6855 synchronized (mGlobalLock) {
6856 final StringWriter sw = new StringWriter();
6857 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6858 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6859 if (reason != null) {
6860 pw.println(" Reason: " + reason);
6861 }
6862 pw.println();
6863 getActivityStartController().dump(pw, " ", null);
6864 pw.println();
6865 pw.println("-------------------------------------------------------------------------------");
6866 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6867 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6868 "" /* header */);
6869 pw.println();
6870 pw.close();
6871
6872 mLastANRState = sw.toString();
6873 }
6874 }
6875
6876 @Override
6877 public void clearSavedANRState() {
6878 synchronized (mGlobalLock) {
6879 mLastANRState = null;
6880 }
6881 }
6882
6883 @Override
6884 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6885 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6886 synchronized (mGlobalLock) {
6887 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6888 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6889 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6890 dumpLastANRLocked(pw);
6891 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6892 dumpLastANRTracesLocked(pw);
6893 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6894 dumpActivityStarterLocked(pw, dumpPackage);
6895 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6896 dumpActivityContainersLocked(pw);
6897 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6898 if (getRecentTasks() != null) {
6899 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6900 }
6901 }
6902 }
6903 }
6904
6905 @Override
6906 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6907 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6908 int wakefulness) {
6909 synchronized (mGlobalLock) {
6910 if (mHomeProcess != null && (dumpPackage == null
6911 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6912 if (needSep) {
6913 pw.println();
6914 needSep = false;
6915 }
6916 pw.println(" mHomeProcess: " + mHomeProcess);
6917 }
6918 if (mPreviousProcess != null && (dumpPackage == null
6919 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6920 if (needSep) {
6921 pw.println();
6922 needSep = false;
6923 }
6924 pw.println(" mPreviousProcess: " + mPreviousProcess);
6925 }
6926 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6927 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6928 StringBuilder sb = new StringBuilder(128);
6929 sb.append(" mPreviousProcessVisibleTime: ");
6930 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6931 pw.println(sb);
6932 }
6933 if (mHeavyWeightProcess != null && (dumpPackage == null
6934 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6935 if (needSep) {
6936 pw.println();
6937 needSep = false;
6938 }
6939 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6940 }
6941 if (dumpPackage == null) {
6942 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006943 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 }
6945 if (dumpAll) {
6946 if (dumpPackage == null) {
6947 pw.println(" mConfigWillChange: "
6948 + getTopDisplayFocusedStack().mConfigWillChange);
6949 }
6950 if (mCompatModePackages.getPackages().size() > 0) {
6951 boolean printed = false;
6952 for (Map.Entry<String, Integer> entry
6953 : mCompatModePackages.getPackages().entrySet()) {
6954 String pkg = entry.getKey();
6955 int mode = entry.getValue();
6956 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6957 continue;
6958 }
6959 if (!printed) {
6960 pw.println(" mScreenCompatPackages:");
6961 printed = true;
6962 }
6963 pw.println(" " + pkg + ": " + mode);
6964 }
6965 }
6966 }
6967
6968 if (dumpPackage == null) {
6969 pw.println(" mWakefulness="
6970 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006971 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006972 if (mRunningVoice != null) {
6973 pw.println(" mRunningVoice=" + mRunningVoice);
6974 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6975 }
6976 pw.println(" mSleeping=" + mSleeping);
6977 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6978 pw.println(" mVrController=" + mVrController);
6979 }
6980 if (mCurAppTimeTracker != null) {
6981 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6982 }
6983 if (mAllowAppSwitchUids.size() > 0) {
6984 boolean printed = false;
6985 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6986 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6987 for (int j = 0; j < types.size(); j++) {
6988 if (dumpPackage == null ||
6989 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6990 if (needSep) {
6991 pw.println();
6992 needSep = false;
6993 }
6994 if (!printed) {
6995 pw.println(" mAllowAppSwitchUids:");
6996 printed = true;
6997 }
6998 pw.print(" User ");
6999 pw.print(mAllowAppSwitchUids.keyAt(i));
7000 pw.print(": Type ");
7001 pw.print(types.keyAt(j));
7002 pw.print(" = ");
7003 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7004 pw.println();
7005 }
7006 }
7007 }
7008 }
7009 if (dumpPackage == null) {
7010 if (mController != null) {
7011 pw.println(" mController=" + mController
7012 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7013 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007014 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7015 pw.println(" mLaunchingActivityWakeLock="
7016 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 }
7018
7019 return needSep;
7020 }
7021 }
7022
7023 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007024 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7025 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007026 synchronized (mGlobalLock) {
7027 if (dumpPackage == null) {
7028 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7029 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007030 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7031 if (mRunningVoice != null) {
7032 final long vrToken = proto.start(
7033 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7034 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7035 mRunningVoice.toString());
7036 mVoiceWakeLock.writeToProto(
7037 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7038 proto.end(vrToken);
7039 }
7040 mVrController.writeToProto(proto,
7041 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007042 if (mController != null) {
7043 final long token = proto.start(CONTROLLER);
7044 proto.write(CONTROLLER, mController.toString());
7045 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7046 proto.end(token);
7047 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007048 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7049 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7050 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007051 }
7052
7053 if (mHomeProcess != null && (dumpPackage == null
7054 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007055 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007056 }
7057
7058 if (mPreviousProcess != null && (dumpPackage == null
7059 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007060 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007061 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7062 }
7063
7064 if (mHeavyWeightProcess != null && (dumpPackage == null
7065 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007066 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007067 }
7068
7069 for (Map.Entry<String, Integer> entry
7070 : mCompatModePackages.getPackages().entrySet()) {
7071 String pkg = entry.getKey();
7072 int mode = entry.getValue();
7073 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7074 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7075 proto.write(PACKAGE, pkg);
7076 proto.write(MODE, mode);
7077 proto.end(compatToken);
7078 }
7079 }
7080
7081 if (mCurAppTimeTracker != null) {
7082 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7083 }
7084
7085 }
7086 }
7087
7088 @Override
7089 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7090 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7091 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007092 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7093 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 }
7095
7096 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007097 public void dumpForOom(PrintWriter pw) {
7098 synchronized (mGlobalLock) {
7099 pw.println(" mHomeProcess: " + mHomeProcess);
7100 pw.println(" mPreviousProcess: " + mPreviousProcess);
7101 if (mHeavyWeightProcess != null) {
7102 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7103 }
7104 }
7105 }
7106
7107 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007108 public boolean canGcNow() {
7109 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007110 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007111 }
7112 }
7113
Riddle Hsua0536432019-02-16 00:38:59 +08007114 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 @Override
7116 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007117 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007118 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 return top != null ? top.app : null;
7120 }
7121 }
7122
Riddle Hsua0536432019-02-16 00:38:59 +08007123 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 @Override
7125 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007126 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007127 if (mRootActivityContainer != null) {
7128 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 }
7130 }
7131 }
7132
7133 @Override
7134 public void scheduleDestroyAllActivities(String reason) {
7135 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007136 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 }
7138 }
7139
7140 @Override
7141 public void removeUser(int userId) {
7142 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007143 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007144 }
7145 }
7146
7147 @Override
7148 public boolean switchUser(int userId, UserState userState) {
7149 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007150 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152 }
7153
7154 @Override
7155 public void onHandleAppCrash(WindowProcessController wpc) {
7156 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007157 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007158 }
7159 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007160
7161 @Override
7162 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7163 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007164 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007165 }
7166 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007167
Riddle Hsua0536432019-02-16 00:38:59 +08007168 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007169 @Override
7170 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007171 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007172 }
7173
Riddle Hsua0536432019-02-16 00:38:59 +08007174 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007175 @Override
7176 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007177 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007178 }
7179
Riddle Hsua0536432019-02-16 00:38:59 +08007180 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007181 @Override
7182 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007183 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007184 }
7185
Riddle Hsua0536432019-02-16 00:38:59 +08007186 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007187 @Override
7188 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007189 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007190 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007191
7192 @Override
7193 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007194 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007195 mPendingTempWhitelist.put(uid, tag);
7196 }
7197 }
7198
7199 @Override
7200 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007201 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007202 mPendingTempWhitelist.remove(uid);
7203 }
7204 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007205
7206 @Override
7207 public boolean handleAppCrashInActivityController(String processName, int pid,
7208 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7209 Runnable killCrashingAppCallback) {
7210 synchronized (mGlobalLock) {
7211 if (mController == null) {
7212 return false;
7213 }
7214
7215 try {
7216 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7217 stackTrace)) {
7218 killCrashingAppCallback.run();
7219 return true;
7220 }
7221 } catch (RemoteException e) {
7222 mController = null;
7223 Watchdog.getInstance().setActivityController(null);
7224 }
7225 return false;
7226 }
7227 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007228
7229 @Override
7230 public void removeRecentTasksByPackageName(String packageName, int userId) {
7231 synchronized (mGlobalLock) {
7232 mRecentTasks.removeTasksByPackageName(packageName, userId);
7233 }
7234 }
7235
7236 @Override
7237 public void cleanupRecentTasksForUser(int userId) {
7238 synchronized (mGlobalLock) {
7239 mRecentTasks.cleanupLocked(userId);
7240 }
7241 }
7242
7243 @Override
7244 public void loadRecentTasksForUser(int userId) {
7245 synchronized (mGlobalLock) {
7246 mRecentTasks.loadUserRecentsLocked(userId);
7247 }
7248 }
7249
7250 @Override
7251 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7252 synchronized (mGlobalLock) {
7253 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7254 }
7255 }
7256
7257 @Override
7258 public void flushRecentTasks() {
7259 mRecentTasks.flush();
7260 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007261
7262 @Override
7263 public WindowProcessController getHomeProcess() {
7264 synchronized (mGlobalLock) {
7265 return mHomeProcess;
7266 }
7267 }
7268
7269 @Override
7270 public WindowProcessController getPreviousProcess() {
7271 synchronized (mGlobalLock) {
7272 return mPreviousProcess;
7273 }
7274 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007275
7276 @Override
7277 public void clearLockedTasks(String reason) {
7278 synchronized (mGlobalLock) {
7279 getLockTaskController().clearLockedTasks(reason);
7280 }
7281 }
7282
7283 @Override
7284 public void updateUserConfiguration() {
7285 synchronized (mGlobalLock) {
7286 final Configuration configuration = new Configuration(getGlobalConfiguration());
7287 final int currentUserId = mAmInternal.getCurrentUserId();
7288 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7289 configuration, currentUserId, Settings.System.canWrite(mContext));
7290 updateConfigurationLocked(configuration, null /* starting */,
7291 false /* initLocale */, false /* persistent */, currentUserId,
7292 false /* deferResume */);
7293 }
7294 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007295
7296 @Override
7297 public boolean canShowErrorDialogs() {
7298 synchronized (mGlobalLock) {
7299 return mShowDialogs && !mSleeping && !mShuttingDown
7300 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7301 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7302 mAmInternal.getCurrentUserId())
7303 && !(UserManager.isDeviceInDemoMode(mContext)
7304 && mAmInternal.getCurrentUser().isDemo());
7305 }
7306 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007307
7308 @Override
7309 public void setProfileApp(String profileApp) {
7310 synchronized (mGlobalLock) {
7311 mProfileApp = profileApp;
7312 }
7313 }
7314
7315 @Override
7316 public void setProfileProc(WindowProcessController wpc) {
7317 synchronized (mGlobalLock) {
7318 mProfileProc = wpc;
7319 }
7320 }
7321
7322 @Override
7323 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7324 synchronized (mGlobalLock) {
7325 mProfilerInfo = profilerInfo;
7326 }
7327 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007328
7329 @Override
7330 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7331 synchronized (mGlobalLock) {
7332 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7333 }
7334 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007335
7336 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007337 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7338 boolean reducedResolution) {
7339 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7340 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007341 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007342
7343 @Override
7344 public boolean isUidForeground(int uid) {
7345 synchronized (mGlobalLock) {
7346 return ActivityTaskManagerService.this.isUidForeground(uid);
7347 }
7348 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007349
7350 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007351 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007352 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007353 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007354 }
7355 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007356
7357 @Override
7358 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007359 // Translate package names into UIDs
7360 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007361 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007362 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7363 if (uid >= 0) {
7364 result.add(uid);
7365 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007366 }
7367 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007368 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007369 }
7370 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007371 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007372}