blob: a683ccb3f7ffde1390eceec77e867106987ffda9 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070086import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
87import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
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 Roskyddedfd42019-10-04 13:38:38 -0700229import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700230import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700231
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700233import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700237import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700240import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
241import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700243import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700244import com.android.internal.policy.IKeyguardDismissCallback;
245import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700246import com.android.internal.util.ArrayUtils;
247import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700248import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700249import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700250import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.LocalServices;
252import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700253import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800254import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700256import com.android.server.am.ActivityManagerService;
257import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
258import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
259import com.android.server.am.AppTimeTracker;
260import com.android.server.am.BaseErrorDialog;
261import com.android.server.am.EventLogTags;
262import com.android.server.am.PendingIntentController;
263import com.android.server.am.PendingIntentRecord;
264import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900265import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700292import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700294import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700295import java.util.Map;
296import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297
298/**
299 * System service for managing activities and their containers (task, stacks, displays,... ).
300 *
301 * {@hide}
302 */
303public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700305 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700306 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
307 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
308 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
309 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
310 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700311 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700312
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100317 // How long we permit background activity starts after an activity in the process
318 // started or finished.
319 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320
Wale Ogunwale98875612018-10-12 07:53:02 -0700321 /** Used to indicate that an app transition should be animated. */
322 static final boolean ANIMATE = true;
323
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700324 /** Hardware-reported OpenGLES version. */
325 final int GL_ES_VERSION;
326
Wale Ogunwale31913b52018-10-13 08:29:31 -0700327 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
328 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
329 public static final String DUMP_LASTANR_CMD = "lastanr" ;
330 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
331 public static final String DUMP_STARTER_CMD = "starter" ;
332 public static final String DUMP_CONTAINERS_CMD = "containers" ;
333 public static final String DUMP_RECENTS_CMD = "recents" ;
334 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
335
Wale Ogunwale64258362018-10-16 15:13:37 -0700336 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
337 public static final int RELAUNCH_REASON_NONE = 0;
338 /** This activity is being relaunched due to windowing mode change. */
339 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
340 /** This activity is being relaunched due to a free-resize operation. */
341 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
342
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700343 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700344
Wale Ogunwalef6733932018-06-27 05:14:34 -0700345 /**
346 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
347 * change at runtime. Use mContext for non-UI purposes.
348 */
349 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700351 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700354 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700355 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800356 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800357 @VisibleForTesting
358 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 PowerManagerInternal mPowerManagerInternal;
360 private UsageStatsManagerInternal mUsageStatsInternal;
361
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700362 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 IntentFirewall mIntentFirewall;
364
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700365 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800366 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700368 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
370 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
371 *
372 * @see WindowManagerThreadPriorityBooster
373 */
374 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800376 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700377 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private UserManagerService mUserManager;
379 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700380 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800381 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700382 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** All processes currently running that might have a window organized by name. */
384 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100385 /** All processes we currently have running mapped by pid and uid */
386 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** This is the process holding what we currently consider to be the "home" activity. */
388 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700389 /** The currently running heavy-weight process, if any. */
390 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700391 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /**
393 * This is the process holding the activity the user last visited that is in a different process
394 * from the one they are currently in.
395 */
396 WindowProcessController mPreviousProcess;
397 /** The time at which the previous process was last visible. */
398 long mPreviousProcessVisibleTime;
399
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700400 /** List of intents that were used to start the most recent tasks. */
401 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700402 /** State of external calls telling us if the device is awake or asleep. */
403 private boolean mKeyguardShown = false;
404
405 // Wrapper around VoiceInteractionServiceManager
406 private AssistUtils mAssistUtils;
407
408 // VoiceInteraction session ID that changes for each new request except when
409 // being called for multi-window assist in a single session.
410 private int mViSessionId = 1000;
411
412 // How long to wait in getAssistContextExtras for the activity and foreground services
413 // to respond with the result.
414 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
415
416 // How long top wait when going through the modern assist (which doesn't need to block
417 // on getting this result before starting to launch its UI).
418 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
419
420 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
421 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
422
Alison Cichowlas3e340502018-08-07 17:15:01 -0400423 // Permission tokens are used to temporarily granted a trusted app the ability to call
424 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
425 // showing any appropriate error messages to the user.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
427 10 * MINUTE_IN_MILLIS;
428
429 // How long before the service actually expires a token. This is slightly longer than
430 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
431 // expiration exception.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
433 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
434
435 // How long the service will remember expired tokens, for the purpose of providing error
436 // messaging when a client uses an expired token.
437 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
438 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
439
440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700466 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700553
554 /**
555 * Flag that indicates if multi-window is enabled.
556 *
557 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
558 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
559 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
560 * At least one of the forms of multi-window must be enabled in order for this flag to be
561 * initialized to 'true'.
562 *
563 * @see #mSupportsSplitScreenMultiWindow
564 * @see #mSupportsFreeformWindowManagement
565 * @see #mSupportsPictureInPicture
566 * @see #mSupportsMultiDisplay
567 */
568 boolean mSupportsMultiWindow;
569 boolean mSupportsSplitScreenMultiWindow;
570 boolean mSupportsFreeformWindowManagement;
571 boolean mSupportsPictureInPicture;
572 boolean mSupportsMultiDisplay;
573 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700574 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
Riddle Hsua0022cd2019-09-09 21:12:41 +0800602 @Retention(RetentionPolicy.SOURCE)
603 @IntDef({
604 LAYOUT_REASON_CONFIG_CHANGED,
605 LAYOUT_REASON_VISIBILITY_CHANGED,
606 })
607 @interface LayoutReason {}
608 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
609 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
610
611 /** The reasons to perform surface placement. */
612 @LayoutReason
613 private int mLayoutReasons;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
616 // automatically. Important for devices without direct input devices.
617 private boolean mShowDialogs = true;
618
619 /** Set if we are shutting down the system, similar to sleeping. */
620 boolean mShuttingDown = false;
621
622 /**
623 * We want to hold a wake lock while running a voice interaction session, since
624 * this may happen with the screen off and we need to keep the CPU running to
625 * be able to continue to interact with the user.
626 */
627 PowerManager.WakeLock mVoiceWakeLock;
628
629 /**
630 * Set while we are running a voice interaction. This overrides sleeping while it is active.
631 */
632 IVoiceInteractionSession mRunningVoice;
633
634 /**
635 * The last resumed activity. This is identical to the current resumed activity most
636 * of the time but could be different when we're pausing one activity before we resume
637 * another activity.
638 */
639 ActivityRecord mLastResumedActivity;
640
641 /**
642 * The activity that is currently being traced as the active resumed activity.
643 *
644 * @see #updateResumedAppTrace
645 */
646 private @Nullable ActivityRecord mTracedResumedActivity;
647
648 /** If non-null, we are tracking the time the user spends in the currently focused app. */
649 AppTimeTracker mCurAppTimeTracker;
650
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700651 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700652
Wale Ogunwale53783742018-09-16 10:21:51 -0700653 /**
654 * Packages that the user has asked to have run in screen size
655 * compatibility mode instead of filling the screen.
656 */
657 CompatModePackages mCompatModePackages;
658
Wale Ogunwalef6733932018-06-27 05:14:34 -0700659 private FontScaleSettingObserver mFontScaleSettingObserver;
660
Ricky Wai96f5c352019-04-10 18:40:17 +0100661 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000662
Wale Ogunwalef6733932018-06-27 05:14:34 -0700663 private final class FontScaleSettingObserver extends ContentObserver {
664 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
665 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
666
667 public FontScaleSettingObserver() {
668 super(mH);
669 final ContentResolver resolver = mContext.getContentResolver();
670 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
671 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
672 UserHandle.USER_ALL);
673 }
674
675 @Override
676 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
677 if (mFontScaleUri.equals(uri)) {
678 updateFontScaleIfNeeded(userId);
679 } else if (mHideErrorDialogsUri.equals(uri)) {
680 synchronized (mGlobalLock) {
681 updateShouldShowDialogsLocked(getGlobalConfiguration());
682 }
683 }
684 }
685 }
686
Riddle Hsua0536432019-02-16 00:38:59 +0800687 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
688 @Target(ElementType.METHOD)
689 @Retention(RetentionPolicy.SOURCE)
690 @interface HotPath {
691 int NONE = 0;
692 int OOM_ADJUSTMENT = 1;
693 int LRU_UPDATE = 2;
694 int PROCESS_CHANGE = 3;
695 int caller() default NONE;
696 }
697
Charles Chen8d98dd22018-12-26 17:36:54 +0800698 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
699 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700700 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700701 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700702 mSystemThread = ActivityThread.currentActivityThread();
703 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700704 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800705 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700706 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700707 }
708
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700709 public void onSystemReady() {
710 synchronized (mGlobalLock) {
711 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
712 PackageManager.FEATURE_CANT_SAVE_STATE);
713 mAssistUtils = new AssistUtils(mContext);
714 mVrController.onSystemReady();
715 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700716 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700718 }
719
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700720 public void onInitPowerManagement() {
721 synchronized (mGlobalLock) {
722 mStackSupervisor.initPowerManagement();
723 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
724 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
725 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
726 mVoiceWakeLock.setReferenceCounted(false);
727 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700731 mFontScaleSettingObserver = new FontScaleSettingObserver();
732 }
733
Wale Ogunwale59507092018-10-29 09:00:30 -0700734 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 final boolean freeformWindowManagement =
736 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
737 || Settings.Global.getInt(
738 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
739
740 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
741 final boolean supportsPictureInPicture = supportsMultiWindow &&
742 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
743 final boolean supportsSplitScreenMultiWindow =
744 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
745 final boolean supportsMultiDisplay = mContext.getPackageManager()
746 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
748 final boolean forceResizable = Settings.Global.getInt(
749 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700750 final boolean sizeCompatFreeform = Settings.Global.getInt(
751 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700752
753 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900754 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700755
756 final Configuration configuration = new Configuration();
757 Settings.System.getConfiguration(resolver, configuration);
758 if (forceRtl) {
759 // This will take care of setting the correct layout direction flags
760 configuration.setLayoutDirection(configuration.locale);
761 }
762
763 synchronized (mGlobalLock) {
764 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700765 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766 final boolean multiWindowFormEnabled = freeformWindowManagement
767 || supportsSplitScreenMultiWindow
768 || supportsPictureInPicture
769 || supportsMultiDisplay;
770 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
771 mSupportsMultiWindow = true;
772 mSupportsFreeformWindowManagement = freeformWindowManagement;
773 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
774 mSupportsPictureInPicture = supportsPictureInPicture;
775 mSupportsMultiDisplay = supportsMultiDisplay;
776 } else {
777 mSupportsMultiWindow = false;
778 mSupportsFreeformWindowManagement = false;
779 mSupportsSplitScreenMultiWindow = false;
780 mSupportsPictureInPicture = false;
781 mSupportsMultiDisplay = false;
782 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700783 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700784 // This happens before any activities are started, so we can change global configuration
785 // in-place.
786 updateConfigurationLocked(configuration, null, true);
787 final Configuration globalConfig = getGlobalConfiguration();
788 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
789
790 // Load resources only after the current configuration has been set.
791 final Resources res = mContext.getResources();
792 mThumbnailWidth = res.getDimensionPixelSize(
793 com.android.internal.R.dimen.thumbnail_width);
794 mThumbnailHeight = res.getDimensionPixelSize(
795 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700796 }
797 }
798
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800799 public WindowManagerGlobalLock getGlobalLock() {
800 return mGlobalLock;
801 }
802
Yunfan Chen585f2932019-01-29 16:04:45 +0900803 /** For test purpose only. */
804 @VisibleForTesting
805 public ActivityTaskManagerInternal getAtmInternal() {
806 return mInternal;
807 }
808
Riddle Hsud93a6c42018-11-29 21:50:06 +0800809 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
810 Looper looper) {
811 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700812 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700813 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700814 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800815 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700816 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700817 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818
819 mTempConfig.setToDefaults();
820 mTempConfig.setLocales(LocaleList.getDefault());
821 mConfigurationSeq = mTempConfig.seq = 1;
822 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800823 mRootActivityContainer = new RootActivityContainer(this);
824 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700825
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700826 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700827 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700828 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700830 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mKeyguardController = mStackSupervisor.getKeyguardController();
833 }
834
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700835 public void onActivityManagerInternalAdded() {
836 synchronized (mGlobalLock) {
837 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
838 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
839 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700840 }
841
Yunfan Chen75157d72018-07-27 14:47:21 +0900842 int increaseConfigurationSeqLocked() {
843 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
844 return mConfigurationSeq;
845 }
846
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700847 protected ActivityStackSupervisor createStackSupervisor() {
848 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
849 supervisor.initialize();
850 return supervisor;
851 }
852
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800853 protected AppWarnings createAppWarnings(
854 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
855 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
856 }
857
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 public void setWindowManager(WindowManagerService wm) {
859 synchronized (mGlobalLock) {
860 mWindowManager = wm;
861 mLockTaskController.setWindowManager(wm);
862 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800863 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700864 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700865 }
866
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700867 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
868 synchronized (mGlobalLock) {
869 mUsageStatsInternal = usageStatsManager;
870 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700871 }
872
Wale Ogunwalef6733932018-06-27 05:14:34 -0700873 UserManagerService getUserManager() {
874 if (mUserManager == null) {
875 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
876 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
877 }
878 return mUserManager;
879 }
880
881 AppOpsService getAppOpsService() {
882 if (mAppOpsService == null) {
883 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
884 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
885 }
886 return mAppOpsService;
887 }
888
889 boolean hasUserRestriction(String restriction, int userId) {
890 return getUserManager().hasUserRestriction(restriction, userId);
891 }
892
Michal Karpinski15486842019-04-25 17:33:42 +0100893 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
894 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700895 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100896 if (mode == AppOpsManager.MODE_DEFAULT) {
897 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
898 == PERMISSION_GRANTED;
899 }
900 return mode == AppOpsManager.MODE_ALLOWED;
901 }
902
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700903 @VisibleForTesting
904 protected void setRecentTasks(RecentTasks recentTasks) {
905 mRecentTasks = recentTasks;
906 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700907 }
908
909 RecentTasks getRecentTasks() {
910 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700911 }
912
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700913 ClientLifecycleManager getLifecycleManager() {
914 return mLifecycleManager;
915 }
916
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700917 ActivityStartController getActivityStartController() {
918 return mActivityStartController;
919 }
920
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700921 TaskChangeNotificationController getTaskChangeNotificationController() {
922 return mTaskChangeNotificationController;
923 }
924
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700925 LockTaskController getLockTaskController() {
926 return mLockTaskController;
927 }
928
Yunfan Chen75157d72018-07-27 14:47:21 +0900929 /**
930 * Return the global configuration used by the process corresponding to the input pid. This is
931 * usually the global configuration with some overrides specific to that process.
932 */
933 Configuration getGlobalConfigurationForCallingPid() {
934 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800935 return getGlobalConfigurationForPid(pid);
936 }
937
938 /**
939 * Return the global configuration used by the process corresponding to the given pid.
940 */
941 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 if (pid == MY_PID || pid < 0) {
943 return getGlobalConfiguration();
944 }
945 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100946 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900947 return app != null ? app.getConfiguration() : getGlobalConfiguration();
948 }
949 }
950
951 /**
952 * Return the device configuration info used by the process corresponding to the input pid.
953 * The value is consistent with the global configuration for the process.
954 */
955 @Override
956 public ConfigurationInfo getDeviceConfigurationInfo() {
957 ConfigurationInfo config = new ConfigurationInfo();
958 synchronized (mGlobalLock) {
959 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
960 config.reqTouchScreen = globalConfig.touchscreen;
961 config.reqKeyboardType = globalConfig.keyboard;
962 config.reqNavigation = globalConfig.navigation;
963 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
964 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
965 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
966 }
967 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
968 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
969 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
970 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700971 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900972 }
973 return config;
974 }
975
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700976 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700977 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700978 }
979
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 public static final class Lifecycle extends SystemService {
981 private final ActivityTaskManagerService mService;
982
983 public Lifecycle(Context context) {
984 super(context);
985 mService = new ActivityTaskManagerService(context);
986 }
987
988 @Override
989 public void onStart() {
990 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 }
993
Garfield Tan891146c2018-10-09 12:14:00 -0700994 @Override
995 public void onUnlockUser(int userId) {
996 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800997 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700998 }
999 }
1000
1001 @Override
1002 public void onCleanupUser(int userId) {
1003 synchronized (mService.getGlobalLock()) {
1004 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1005 }
1006 }
1007
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001008 public ActivityTaskManagerService getService() {
1009 return mService;
1010 }
1011 }
1012
1013 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001014 public final int startActivity(IApplicationThread caller, String callingPackage,
1015 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1016 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1017 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1018 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1019 UserHandle.getCallingUserId());
1020 }
1021
1022 @Override
1023 public final int startActivities(IApplicationThread caller, String callingPackage,
1024 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1025 int userId) {
1026 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001027 enforceNotIsolatedCaller(reason);
1028 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001029 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001030 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1031 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1032 reason, null /* originatingPendingIntent */,
1033 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 }
1035
1036 @Override
1037 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1038 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1039 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1040 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1041 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1042 true /*validateIncomingUser*/);
1043 }
1044
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001045 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1047 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1048 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001049 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001051 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001052 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1053
1054 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001055 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 .setCaller(caller)
1057 .setCallingPackage(callingPackage)
1058 .setResolvedType(resolvedType)
1059 .setResultTo(resultTo)
1060 .setResultWho(resultWho)
1061 .setRequestCode(requestCode)
1062 .setStartFlags(startFlags)
1063 .setProfilerInfo(profilerInfo)
1064 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001065 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .execute();
1067
1068 }
1069
1070 @Override
1071 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1072 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001073 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1074 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 // Refuse possible leaked file descriptors
1076 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1077 throw new IllegalArgumentException("File descriptors passed in Intent");
1078 }
1079
1080 if (!(target instanceof PendingIntentRecord)) {
1081 throw new IllegalArgumentException("Bad PendingIntent object");
1082 }
1083
1084 PendingIntentRecord pir = (PendingIntentRecord)target;
1085
1086 synchronized (mGlobalLock) {
1087 // If this is coming from the currently resumed activity, it is
1088 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001089 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 if (stack.mResumedActivity != null &&
1091 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001092 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001093 }
1094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001095 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001097 }
1098
1099 @Override
1100 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1101 Bundle bOptions) {
1102 // Refuse possible leaked file descriptors
1103 if (intent != null && intent.hasFileDescriptors()) {
1104 throw new IllegalArgumentException("File descriptors passed in Intent");
1105 }
1106 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1107
1108 synchronized (mGlobalLock) {
1109 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1110 if (r == null) {
1111 SafeActivityOptions.abort(options);
1112 return false;
1113 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001114 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001115 // The caller is not running... d'oh!
1116 SafeActivityOptions.abort(options);
1117 return false;
1118 }
1119 intent = new Intent(intent);
1120 // The caller is not allowed to change the data.
1121 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1122 // And we are resetting to find the next component...
1123 intent.setComponent(null);
1124
1125 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1126
1127 ActivityInfo aInfo = null;
1128 try {
1129 List<ResolveInfo> resolves =
1130 AppGlobals.getPackageManager().queryIntentActivities(
1131 intent, r.resolvedType,
1132 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1133 UserHandle.getCallingUserId()).getList();
1134
1135 // Look for the original activity in the list...
1136 final int N = resolves != null ? resolves.size() : 0;
1137 for (int i=0; i<N; i++) {
1138 ResolveInfo rInfo = resolves.get(i);
1139 if (rInfo.activityInfo.packageName.equals(r.packageName)
1140 && rInfo.activityInfo.name.equals(r.info.name)) {
1141 // We found the current one... the next matching is
1142 // after it.
1143 i++;
1144 if (i<N) {
1145 aInfo = resolves.get(i).activityInfo;
1146 }
1147 if (debug) {
1148 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1149 + "/" + r.info.name);
1150 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1151 ? "null" : aInfo.packageName + "/" + aInfo.name));
1152 }
1153 break;
1154 }
1155 }
1156 } catch (RemoteException e) {
1157 }
1158
1159 if (aInfo == null) {
1160 // Nobody who is next!
1161 SafeActivityOptions.abort(options);
1162 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1163 return false;
1164 }
1165
1166 intent.setComponent(new ComponentName(
1167 aInfo.applicationInfo.packageName, aInfo.name));
1168 intent.setFlags(intent.getFlags()&~(
1169 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1170 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1171 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1172 FLAG_ACTIVITY_NEW_TASK));
1173
1174 // Okay now we need to start the new activity, replacing the currently running activity.
1175 // This is a little tricky because we want to start the new one as if the current one is
1176 // finished, but not finish the current one first so that there is no flicker.
1177 // And thus...
1178 final boolean wasFinishing = r.finishing;
1179 r.finishing = true;
1180
1181 // Propagate reply information over to the new activity.
1182 final ActivityRecord resultTo = r.resultTo;
1183 final String resultWho = r.resultWho;
1184 final int requestCode = r.requestCode;
1185 r.resultTo = null;
1186 if (resultTo != null) {
1187 resultTo.removeResultsLocked(r, resultWho, requestCode);
1188 }
1189
1190 final long origId = Binder.clearCallingIdentity();
1191 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001192 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001193 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001194 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001195 .setResolvedType(r.resolvedType)
1196 .setActivityInfo(aInfo)
1197 .setResultTo(resultTo != null ? resultTo.appToken : null)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setCallingPid(-1)
1201 .setCallingUid(r.launchedFromUid)
1202 .setCallingPackage(r.launchedFromPackage)
1203 .setRealCallingPid(-1)
1204 .setRealCallingUid(r.launchedFromUid)
1205 .setActivityOptions(options)
1206 .execute();
1207 Binder.restoreCallingIdentity(origId);
1208
1209 r.finishing = wasFinishing;
1210 if (res != ActivityManager.START_SUCCESS) {
1211 return false;
1212 }
1213 return true;
1214 }
1215 }
1216
1217 @Override
1218 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1219 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1220 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1221 final WaitResult res = new WaitResult();
1222 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001223 enforceNotIsolatedCaller("startActivityAndWait");
1224 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1225 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001226 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001227 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001228 .setCaller(caller)
1229 .setCallingPackage(callingPackage)
1230 .setResolvedType(resolvedType)
1231 .setResultTo(resultTo)
1232 .setResultWho(resultWho)
1233 .setRequestCode(requestCode)
1234 .setStartFlags(startFlags)
1235 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001236 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 .setProfilerInfo(profilerInfo)
1238 .setWaitResult(res)
1239 .execute();
1240 }
1241 return res;
1242 }
1243
1244 @Override
1245 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1246 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1247 int startFlags, Configuration config, Bundle bOptions, int userId) {
1248 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001249 enforceNotIsolatedCaller("startActivityWithConfig");
1250 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1251 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001252 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001253 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001254 .setCaller(caller)
1255 .setCallingPackage(callingPackage)
1256 .setResolvedType(resolvedType)
1257 .setResultTo(resultTo)
1258 .setResultWho(resultWho)
1259 .setRequestCode(requestCode)
1260 .setStartFlags(startFlags)
1261 .setGlobalConfiguration(config)
1262 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001263 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 .execute();
1265 }
1266 }
1267
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268
1269 @Override
1270 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1271 int callingUid = Binder.getCallingUid();
1272 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1273 throw new SecurityException("Only the system process can request a permission token, "
1274 + "received request from uid: " + callingUid);
1275 }
1276 IBinder permissionToken = new Binder();
1277 synchronized (mGlobalLock) {
1278 mStartActivitySources.put(permissionToken, delegatorToken);
1279 }
1280
1281 Message expireMsg = PooledLambda.obtainMessage(
1282 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1283 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1284
1285 Message forgetMsg = PooledLambda.obtainMessage(
1286 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1287 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1288
1289 return permissionToken;
1290 }
1291
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001292 @Override
1293 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1294 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001295 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1296 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001298 // permission grants) as any app that may launch one of your own activities. So we only
1299 // allow this in two cases:
1300 // 1) The caller is an activity that is part of the core framework, and then only when it
1301 // is running as the system.
1302 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1303 // can only be requested by a system activity, which may then delegate this call to
1304 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 final ActivityRecord sourceRecord;
1306 final int targetUid;
1307 final String targetPackage;
1308 final boolean isResolver;
1309 synchronized (mGlobalLock) {
1310 if (resultTo == null) {
1311 throw new SecurityException("Must be called from an activity");
1312 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001313 final IBinder sourceToken;
1314 if (permissionToken != null) {
1315 // To even attempt to use a permissionToken, an app must also have this signature
1316 // permission.
1317 mAmInternal.enforceCallingPermission(
1318 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1319 "startActivityAsCaller");
1320 // If called with a permissionToken, we want the sourceRecord from the delegator
1321 // activity that requested this token.
1322 sourceToken = mStartActivitySources.remove(permissionToken);
1323 if (sourceToken == null) {
1324 // Invalid permissionToken, check if it recently expired.
1325 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1326 throw new SecurityException("Called with expired permission token: "
1327 + permissionToken);
1328 } else {
1329 throw new SecurityException("Called with invalid permission token: "
1330 + permissionToken);
1331 }
1332 }
1333 } else {
1334 // This method was called directly by the source.
1335 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001336 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001337
Wale Ogunwaled32da472018-11-16 07:19:28 -08001338 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339 if (sourceRecord == null) {
1340 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 }
1342 if (sourceRecord.app == null) {
1343 throw new SecurityException("Called without a process attached to activity");
1344 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345
1346 // Whether called directly or from a delegate, the source activity must be from the
1347 // android package.
1348 if (!sourceRecord.info.packageName.equals("android")) {
1349 throw new SecurityException("Must be called from an activity that is "
1350 + "declared in the android package");
1351 }
1352
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001353 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 // This is still okay, as long as this activity is running under the
1355 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001356 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001358 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 + " must be system uid or original calling uid "
1360 + sourceRecord.launchedFromUid);
1361 }
1362 }
1363 if (ignoreTargetSecurity) {
1364 if (intent.getComponent() == null) {
1365 throw new SecurityException(
1366 "Component must be specified with ignoreTargetSecurity");
1367 }
1368 if (intent.getSelector() != null) {
1369 throw new SecurityException(
1370 "Selector not allowed with ignoreTargetSecurity");
1371 }
1372 }
1373 targetUid = sourceRecord.launchedFromUid;
1374 targetPackage = sourceRecord.launchedFromPackage;
1375 isResolver = sourceRecord.isResolverOrChildActivity();
1376 }
1377
1378 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001379 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 }
1381
1382 // TODO: Switch to user app stacks here.
1383 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001384 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 .setCallingUid(targetUid)
1386 .setCallingPackage(targetPackage)
1387 .setResolvedType(resolvedType)
1388 .setResultTo(resultTo)
1389 .setResultWho(resultWho)
1390 .setRequestCode(requestCode)
1391 .setStartFlags(startFlags)
1392 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001393 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1395 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001396 // The target may well be in the background, which would normally prevent it
1397 // from starting an activity. Here we definitely want the start to succeed.
1398 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 .execute();
1400 } catch (SecurityException e) {
1401 // XXX need to figure out how to propagate to original app.
1402 // A SecurityException here is generally actually a fault of the original
1403 // calling activity (such as a fairly granting permissions), so propagate it
1404 // back to them.
1405 /*
1406 StringBuilder msg = new StringBuilder();
1407 msg.append("While launching");
1408 msg.append(intent.toString());
1409 msg.append(": ");
1410 msg.append(e.getMessage());
1411 */
1412 throw e;
1413 }
1414 }
1415
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1417 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1418 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1419 }
1420
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 @Override
1422 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1423 Intent intent, String resolvedType, IVoiceInteractionSession session,
1424 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1425 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001426 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 if (session == null || interactor == null) {
1428 throw new NullPointerException("null session or interactor");
1429 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001430 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001432 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 .setCallingUid(callingUid)
1434 .setCallingPackage(callingPackage)
1435 .setResolvedType(resolvedType)
1436 .setVoiceSession(session)
1437 .setVoiceInteractor(interactor)
1438 .setStartFlags(startFlags)
1439 .setProfilerInfo(profilerInfo)
1440 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001441 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001442 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .execute();
1444 }
1445
1446 @Override
1447 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1448 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001449 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1450 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001452 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 .setCallingUid(callingUid)
1454 .setCallingPackage(callingPackage)
1455 .setResolvedType(resolvedType)
1456 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001457 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001458 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .execute();
1460 }
1461
Riddle Hsu609a8e22019-06-27 16:46:29 -06001462 /**
1463 * Start the recents activity to perform the recents animation.
1464 *
1465 * @param intent The intent to start the recents activity.
1466 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1467 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1470 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001471 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001473 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 final long origId = Binder.clearCallingIdentity();
1475 try {
1476 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001477 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1478 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480
1481 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001482 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001484 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001485 if (recentsAnimationRunner == null) {
1486 anim.preloadRecentsActivity();
1487 } else {
1488 anim.startRecentsActivity(recentsAnimationRunner);
1489 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001490 }
1491 } finally {
1492 Binder.restoreCallingIdentity(origId);
1493 }
1494 }
1495
1496 @Override
1497 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 "startActivityFromRecents()");
1500
1501 final int callingPid = Binder.getCallingPid();
1502 final int callingUid = Binder.getCallingUid();
1503 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1504 final long origId = Binder.clearCallingIdentity();
1505 try {
1506 synchronized (mGlobalLock) {
1507 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1508 safeOptions);
1509 }
1510 } finally {
1511 Binder.restoreCallingIdentity(origId);
1512 }
1513 }
1514
1515 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001516 * Public API to check if the client is allowed to start an activity on specified display.
1517 *
1518 * If the target display is private or virtual, some restrictions will apply.
1519 *
1520 * @param displayId Target display id.
1521 * @param intent Intent used to launch the activity.
1522 * @param resolvedType The MIME type of the intent.
1523 * @param userId The id of the user for whom the call is made.
1524 * @return {@code true} if a call to start an activity on the target display should succeed and
1525 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1526 */
1527 @Override
1528 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1529 String resolvedType, int userId) {
1530 final int callingUid = Binder.getCallingUid();
1531 final int callingPid = Binder.getCallingPid();
1532 final long origId = Binder.clearCallingIdentity();
1533
1534 try {
1535 // Collect information about the target of the Intent.
1536 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1537 0 /* startFlags */, null /* profilerInfo */, userId,
1538 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1539 UserHandle.USER_NULL));
1540 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1541
1542 synchronized (mGlobalLock) {
1543 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1544 aInfo);
1545 }
1546 } finally {
1547 Binder.restoreCallingIdentity(origId);
1548 }
1549 }
1550
1551 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 * This is the internal entry point for handling Activity.finish().
1553 *
1554 * @param token The Binder token referencing the Activity we want to finish.
1555 * @param resultCode Result code, if any, from this Activity.
1556 * @param resultData Result data (Intent), if any, from this Activity.
1557 * @param finishTask Whether to finish the task associated with this Activity.
1558 *
1559 * @return Returns true if the activity successfully finished, or false if it is still running.
1560 */
1561 @Override
1562 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1563 int finishTask) {
1564 // Refuse possible leaked file descriptors
1565 if (resultData != null && resultData.hasFileDescriptors()) {
1566 throw new IllegalArgumentException("File descriptors passed in Intent");
1567 }
1568
1569 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001570 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (r == null) {
1572 return true;
1573 }
1574 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001575 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001576 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (rootR == null) {
1578 Slog.w(TAG, "Finishing task with all activities already finished");
1579 }
1580 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1581 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001582 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 return false;
1584 }
1585
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001586 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1587 // We should consolidate.
1588 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001590 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (next != null) {
1592 // ask watcher if this is allowed
1593 boolean resumeOK = true;
1594 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001595 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001597 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 Watchdog.getInstance().setActivityController(null);
1599 }
1600
1601 if (!resumeOK) {
1602 Slog.i(TAG, "Not finishing activity because controller resumed");
1603 return false;
1604 }
1605 }
1606 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001607
1608 // note down that the process has finished an activity and is in background activity
1609 // starts grace period
1610 if (r.app != null) {
1611 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1612 }
1613
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001614 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001615 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 try {
1617 boolean res;
1618 final boolean finishWithRootActivity =
1619 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1620 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1621 || (finishWithRootActivity && r == rootR)) {
1622 // If requested, remove the task that is associated to this activity only if it
1623 // was the root activity in the task. The result code and data is ignored
1624 // because we don't support returning them across task boundaries. Also, to
1625 // keep backwards compatibility we remove the task from recents when finishing
1626 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001627 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001628 finishWithRootActivity, "finish-activity");
1629 if (!res) {
1630 Slog.i(TAG, "Removing task failed to finish activity");
1631 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001632 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001633 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001635 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001636 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 if (!res) {
1638 Slog.i(TAG, "Failed to finish by app-request");
1639 }
1640 }
1641 return res;
1642 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001643 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 Binder.restoreCallingIdentity(origId);
1645 }
1646 }
1647 }
1648
1649 @Override
1650 public boolean finishActivityAffinity(IBinder token) {
1651 synchronized (mGlobalLock) {
1652 final long origId = Binder.clearCallingIdentity();
1653 try {
1654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r == null) {
1656 return false;
1657 }
1658
1659 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1660 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001661 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 return false;
1663 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001664 r.finishActivityAffinity();
1665 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 } finally {
1667 Binder.restoreCallingIdentity(origId);
1668 }
1669 }
1670 }
1671
1672 @Override
1673 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1674 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001675 try {
1676 WindowProcessController proc = null;
1677 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001678 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001679 ActivityStack stack = ActivityRecord.getStackLocked(token);
1680 if (stack == null) {
1681 return;
1682 }
1683 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1684 false /* fromTimeout */, false /* processPausingActivities */, config);
1685 if (r != null) {
1686 proc = r.app;
1687 }
1688 if (stopProfiling && proc != null) {
1689 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 }
1691 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001692 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001693 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001694 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001695 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 }
1697
1698 @Override
1699 public final void activityResumed(IBinder token) {
1700 final long origId = Binder.clearCallingIdentity();
1701 synchronized (mGlobalLock) {
1702 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 }
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706
1707 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001708 public final void activityTopResumedStateLost() {
1709 final long origId = Binder.clearCallingIdentity();
1710 synchronized (mGlobalLock) {
1711 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1712 }
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715
1716 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 public final void activityPaused(IBinder token) {
1718 final long origId = Binder.clearCallingIdentity();
1719 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001720 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 ActivityStack stack = ActivityRecord.getStackLocked(token);
1722 if (stack != null) {
1723 stack.activityPausedLocked(token, false);
1724 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001725 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 }
1727 Binder.restoreCallingIdentity(origId);
1728 }
1729
1730 @Override
1731 public final void activityStopped(IBinder token, Bundle icicle,
1732 PersistableBundle persistentState, CharSequence description) {
1733 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1734
1735 // Refuse possible leaked file descriptors
1736 if (icicle != null && icicle.hasFileDescriptors()) {
1737 throw new IllegalArgumentException("File descriptors passed in Bundle");
1738 }
1739
1740 final long origId = Binder.clearCallingIdentity();
1741
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001742 String restartingName = null;
1743 int restartingUid = 0;
1744 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001746 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001747 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001749 if (r.attachedToProcess()
1750 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1751 // The activity was requested to restart from
1752 // {@link #restartActivityProcessIfVisible}.
1753 restartingName = r.app.mName;
1754 restartingUid = r.app.mUid;
1755 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 r.activityStoppedLocked(icicle, persistentState, description);
1757 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001758 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 }
1760
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001761 if (restartingName != null) {
1762 // In order to let the foreground activity can be restarted with its saved state from
1763 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1764 // until the activity reports stopped with the state. And the activity record will be
1765 // kept because the record state is restarting, then the activity will be restarted
1766 // immediately if it is still the top one.
1767 mStackSupervisor.removeRestartTimeouts(r);
1768 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1769 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001770 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771
1772 Binder.restoreCallingIdentity(origId);
1773 }
1774
1775 @Override
1776 public final void activityDestroyed(IBinder token) {
1777 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1778 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001779 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001780 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001781 try {
1782 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1783 if (activity != null) {
1784 activity.destroyed("activityDestroyed");
1785 }
1786 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001787 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001788 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 }
1790 }
1791 }
1792
1793 @Override
1794 public final void activityRelaunched(IBinder token) {
1795 final long origId = Binder.clearCallingIdentity();
1796 synchronized (mGlobalLock) {
1797 mStackSupervisor.activityRelaunchedLocked(token);
1798 }
1799 Binder.restoreCallingIdentity(origId);
1800 }
1801
1802 public final void activitySlept(IBinder token) {
1803 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1804
1805 final long origId = Binder.clearCallingIdentity();
1806
1807 synchronized (mGlobalLock) {
1808 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1809 if (r != null) {
1810 mStackSupervisor.activitySleptLocked(r);
1811 }
1812 }
1813
1814 Binder.restoreCallingIdentity(origId);
1815 }
1816
1817 @Override
1818 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1819 synchronized (mGlobalLock) {
1820 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r == null) {
1822 return;
1823 }
1824 final long origId = Binder.clearCallingIdentity();
1825 try {
1826 r.setRequestedOrientation(requestedOrientation);
1827 } finally {
1828 Binder.restoreCallingIdentity(origId);
1829 }
1830 }
1831 }
1832
1833 @Override
1834 public int getRequestedOrientation(IBinder token) {
1835 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001836 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1837 return (r != null)
1838 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 }
1840 }
1841
1842 @Override
1843 public void setImmersive(IBinder token, boolean immersive) {
1844 synchronized (mGlobalLock) {
1845 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1846 if (r == null) {
1847 throw new IllegalArgumentException();
1848 }
1849 r.immersive = immersive;
1850
1851 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001852 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001854 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 }
1856 }
1857 }
1858
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001859 void applyUpdateLockStateLocked(ActivityRecord r) {
1860 // Modifications to the UpdateLock state are done on our handler, outside
1861 // the activity manager's locks. The new state is determined based on the
1862 // state *now* of the relevant activity record. The object is passed to
1863 // the handler solely for logging detail, not to be consulted/modified.
1864 final boolean nextState = r != null && r.immersive;
1865 mH.post(() -> {
1866 if (mUpdateLock.isHeld() != nextState) {
1867 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1868 "Applying new update lock state '" + nextState + "' for " + r);
1869 if (nextState) {
1870 mUpdateLock.acquire();
1871 } else {
1872 mUpdateLock.release();
1873 }
1874 }
1875 });
1876 }
1877
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 @Override
1879 public boolean isImmersive(IBinder token) {
1880 synchronized (mGlobalLock) {
1881 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1882 if (r == null) {
1883 throw new IllegalArgumentException();
1884 }
1885 return r.immersive;
1886 }
1887 }
1888
1889 @Override
1890 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001893 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 return (r != null) ? r.immersive : false;
1895 }
1896 }
1897
1898 @Override
1899 public void overridePendingTransition(IBinder token, String packageName,
1900 int enterAnim, int exitAnim) {
1901 synchronized (mGlobalLock) {
1902 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1903 if (self == null) {
1904 return;
1905 }
1906
1907 final long origId = Binder.clearCallingIdentity();
1908
1909 if (self.isState(
1910 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001911 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001912 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 }
1914
1915 Binder.restoreCallingIdentity(origId);
1916 }
1917 }
1918
1919 @Override
1920 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001921 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001923 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001924 if (r == null) {
1925 return ActivityManager.COMPAT_MODE_UNKNOWN;
1926 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001927 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930
1931 @Override
1932 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001933 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001935 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001937 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001938 if (r == null) {
1939 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1940 return;
1941 }
1942 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001943 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 }
1945 }
1946
1947 @Override
1948 public int getLaunchedFromUid(IBinder activityToken) {
1949 ActivityRecord srec;
1950 synchronized (mGlobalLock) {
1951 srec = ActivityRecord.forTokenLocked(activityToken);
1952 }
1953 if (srec == null) {
1954 return -1;
1955 }
1956 return srec.launchedFromUid;
1957 }
1958
1959 @Override
1960 public String getLaunchedFromPackage(IBinder activityToken) {
1961 ActivityRecord srec;
1962 synchronized (mGlobalLock) {
1963 srec = ActivityRecord.forTokenLocked(activityToken);
1964 }
1965 if (srec == null) {
1966 return null;
1967 }
1968 return srec.launchedFromPackage;
1969 }
1970
1971 @Override
1972 public boolean convertFromTranslucent(IBinder token) {
1973 final long origId = Binder.clearCallingIdentity();
1974 try {
1975 synchronized (mGlobalLock) {
1976 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1977 if (r == null) {
1978 return false;
1979 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001980 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 }
1982 } finally {
1983 Binder.restoreCallingIdentity(origId);
1984 }
1985 }
1986
1987 @Override
1988 public boolean convertToTranslucent(IBinder token, Bundle options) {
1989 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1990 final long origId = Binder.clearCallingIdentity();
1991 try {
1992 synchronized (mGlobalLock) {
1993 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1994 if (r == null) {
1995 return false;
1996 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001997 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001998 int index = task.mChildren.lastIndexOf(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002000 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2002 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002003 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002004 }
2005 } finally {
2006 Binder.restoreCallingIdentity(origId);
2007 }
2008 }
2009
2010 @Override
2011 public void notifyActivityDrawn(IBinder token) {
2012 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002014 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002016 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 }
2018 }
2019 }
2020
2021 @Override
2022 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2023 synchronized (mGlobalLock) {
2024 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2025 if (r == null) {
2026 return;
2027 }
2028 r.reportFullyDrawnLocked(restoredFromBundle);
2029 }
2030 }
2031
2032 @Override
2033 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2034 synchronized (mGlobalLock) {
2035 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2036 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2037 return stack.mDisplayId;
2038 }
2039 return DEFAULT_DISPLAY;
2040 }
2041 }
2042
2043 @Override
2044 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046 long ident = Binder.clearCallingIdentity();
2047 try {
2048 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002049 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 return null;
2054 }
2055 } finally {
2056 Binder.restoreCallingIdentity(ident);
2057 }
2058 }
2059
2060 @Override
2061 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002062 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2064 final long callingId = Binder.clearCallingIdentity();
2065 try {
2066 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002067 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (stack == null) {
2069 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2070 return;
2071 }
2072 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002073 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002074 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(callingId);
2079 }
2080 }
2081
2082 @Override
2083 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002089 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002090 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (task == null) {
2092 return;
2093 }
2094 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002095 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002096 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 }
2098 }
2099 } finally {
2100 Binder.restoreCallingIdentity(callingId);
2101 }
2102 }
2103
2104 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002105 public void restartActivityProcessIfVisible(IBinder activityToken) {
2106 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2107 final long callingId = Binder.clearCallingIdentity();
2108 try {
2109 synchronized (mGlobalLock) {
2110 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2111 if (r == null) {
2112 return;
2113 }
2114 r.restartProcessIfVisible();
2115 }
2116 } finally {
2117 Binder.restoreCallingIdentity(callingId);
2118 }
2119 }
2120
2121 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
2127 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2128 "remove-task");
2129 } finally {
2130 Binder.restoreCallingIdentity(ident);
2131 }
2132 }
2133 }
2134
2135 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002136 public void removeAllVisibleRecentTasks() {
2137 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2138 synchronized (mGlobalLock) {
2139 final long ident = Binder.clearCallingIdentity();
2140 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002141 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002142 } finally {
2143 Binder.restoreCallingIdentity(ident);
2144 }
2145 }
2146 }
2147
2148 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2150 synchronized (mGlobalLock) {
2151 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2152 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002153 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 }
2155 }
2156 return false;
2157 }
2158
2159 @Override
2160 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2161 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002162
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002163 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2165 if (r != null) {
2166 return r.getActivityStack().navigateUpToLocked(
2167 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172
2173 /**
2174 * Attempts to move a task backwards in z-order (the order of activities within the task is
2175 * unchanged).
2176 *
2177 * There are several possible results of this call:
2178 * - if the task is locked, then we will show the lock toast
2179 * - if there is a task behind the provided task, then that task is made visible and resumed as
2180 * this task is moved to the back
2181 * - otherwise, if there are no other tasks in the stack:
2182 * - if this task is in the pinned stack, then we remove the stack completely, which will
2183 * have the effect of moving the task to the top or bottom of the fullscreen stack
2184 * (depending on whether it is visible)
2185 * - otherwise, we simply return home and hide this task
2186 *
2187 * @param token A reference to the activity we wish to move
2188 * @param nonRoot If false then this only works if the activity is the root
2189 * of a task; if true it will work for any activity in a task.
2190 * @return Returns true if the move completed, false if not.
2191 */
2192 @Override
2193 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
2198 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002199 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task != null) {
2201 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2202 }
2203 } finally {
2204 Binder.restoreCallingIdentity(origId);
2205 }
2206 }
2207 return false;
2208 }
2209
2210 @Override
2211 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 long ident = Binder.clearCallingIdentity();
2214 Rect rect = new Rect();
2215 try {
2216 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002217 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2219 if (task == null) {
2220 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2221 return rect;
2222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002223 if (task.getParent() != null) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(ident);
2231 }
2232 return rect;
2233 }
2234
2235 @Override
2236 public ActivityManager.TaskDescription getTaskDescription(int id) {
2237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002238 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002240 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002241 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2242 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002243 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245 }
2246 return null;
2247 }
2248
2249 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002250 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2251 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2252 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2253 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2254 return;
2255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 synchronized (mGlobalLock) {
2258 final long ident = Binder.clearCallingIdentity();
2259 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002260 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002261 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 if (task == null) {
2263 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2264 return;
2265 }
2266
2267 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2268 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2269
2270 if (!task.isActivityTypeStandardOrUndefined()) {
2271 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2272 + " non-standard task " + taskId + " to windowing mode="
2273 + windowingMode);
2274 }
2275
2276 final ActivityStack stack = task.getStack();
2277 if (toTop) {
2278 stack.moveToFront("setTaskWindowingMode", task);
2279 }
2280 stack.setWindowingMode(windowingMode);
2281 } finally {
2282 Binder.restoreCallingIdentity(ident);
2283 }
2284 }
2285 }
2286
2287 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 ActivityRecord r = getCallingRecordLocked(token);
2291 return r != null ? r.info.packageName : null;
2292 }
2293 }
2294
2295 @Override
2296 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002297 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 ActivityRecord r = getCallingRecordLocked(token);
2299 return r != null ? r.intent.getComponent() : null;
2300 }
2301 }
2302
2303 private ActivityRecord getCallingRecordLocked(IBinder token) {
2304 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2305 if (r == null) {
2306 return null;
2307 }
2308 return r.resultTo;
2309 }
2310
2311 @Override
2312 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002313 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002314
2315 synchronized (mGlobalLock) {
2316 final long origId = Binder.clearCallingIdentity();
2317 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002318 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 } finally {
2320 Binder.restoreCallingIdentity(origId);
2321 }
2322 }
2323 }
2324
Mark Renouf446251d2019-04-26 10:22:41 -04002325 @Override
2326 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2327 synchronized (mGlobalLock) {
2328 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2329 if (r == null) {
2330 return;
2331 }
2332 ActivityStack stack = r.getActivityStack();
2333 if (stack != null && stack.isSingleTaskInstance()) {
2334 // Single-task stacks are used for activities which are presented in floating
2335 // windows above full screen activities. Instead of directly finishing the
2336 // task, a task change listener is used to notify SystemUI so the action can be
2337 // handled specially.
2338 final TaskRecord task = r.getTaskRecord();
2339 mTaskChangeNotificationController
2340 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2341 } else {
2342 try {
2343 callback.requestFinish();
2344 } catch (RemoteException e) {
2345 Slog.e(TAG, "Failed to invoke request finish callback", e);
2346 }
2347 }
2348 }
2349 }
2350
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 /**
2352 * TODO: Add mController hook
2353 */
2354 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2356 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002358
2359 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2360 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002361 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2362 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363 }
2364 }
2365
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2367 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002369
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 final int callingPid = Binder.getCallingPid();
2371 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002372 if (!isSameApp(callingUid, callingPackage)) {
2373 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2374 + Binder.getCallingPid() + " as package " + callingPackage;
2375 Slog.w(TAG, msg);
2376 throw new SecurityException(msg);
2377 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379 SafeActivityOptions.abort(options);
2380 return;
2381 }
2382 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 WindowProcessController callerApp = null;
2384 if (appThread != null) {
2385 callerApp = getProcessController(appThread);
2386 }
2387 final ActivityStarter starter = getActivityStartController().obtainStarter(
2388 null /* intent */, "moveTaskToFront");
2389 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2390 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002391 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 return;
2393 }
2394 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002396 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 if (task == null) {
2398 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002399 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 return;
2401 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002402 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002404 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 return;
2406 }
2407 ActivityOptions realOptions = options != null
2408 ? options.getOptions(mStackSupervisor)
2409 : null;
2410 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2411 false /* forceNonResizable */);
2412
2413 final ActivityRecord topActivity = task.getTopActivity();
2414 if (topActivity != null) {
2415
2416 // We are reshowing a task, use a starting window to hide the initial draw delay
2417 // so the transition can start earlier.
2418 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2419 true /* taskSwitch */, fromRecents);
2420 }
2421 } finally {
2422 Binder.restoreCallingIdentity(origId);
2423 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 }
2425
Ricky Waiaca8a772019-04-04 16:01:06 +01002426 /**
2427 * Return true if callingUid is system, or packageName belongs to that callingUid.
2428 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002429 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002430 try {
2431 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2432 if (packageName == null) {
2433 return false;
2434 }
2435 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2436 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2437 UserHandle.getUserId(callingUid));
2438 return UserHandle.isSameApp(callingUid, uid);
2439 }
2440 } catch (RemoteException e) {
2441 // Should not happen
2442 }
2443 return true;
2444 }
2445
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002446 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2447 int callingPid, int callingUid, String name) {
2448 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2449 return true;
2450 }
2451
2452 if (getRecentTasks().isCallerRecents(sourceUid)) {
2453 return true;
2454 }
2455
2456 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2457 if (perm == PackageManager.PERMISSION_GRANTED) {
2458 return true;
2459 }
2460 if (checkAllowAppSwitchUid(sourceUid)) {
2461 return true;
2462 }
2463
2464 // If the actual IPC caller is different from the logical source, then
2465 // also see if they are allowed to control app switches.
2466 if (callingUid != -1 && callingUid != sourceUid) {
2467 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2468 if (perm == PackageManager.PERMISSION_GRANTED) {
2469 return true;
2470 }
2471 if (checkAllowAppSwitchUid(callingUid)) {
2472 return true;
2473 }
2474 }
2475
2476 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2477 return false;
2478 }
2479
2480 private boolean checkAllowAppSwitchUid(int uid) {
2481 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2482 if (types != null) {
2483 for (int i = types.size() - 1; i >= 0; i--) {
2484 if (types.valueAt(i).intValue() == uid) {
2485 return true;
2486 }
2487 }
2488 }
2489 return false;
2490 }
2491
2492 @Override
2493 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2494 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2495 "setActivityController()");
2496 synchronized (mGlobalLock) {
2497 mController = controller;
2498 mControllerIsAMonkey = imAMonkey;
2499 Watchdog.getInstance().setActivityController(controller);
2500 }
2501 }
2502
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002503 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002504 synchronized (mGlobalLock) {
2505 return mController != null && mControllerIsAMonkey;
2506 }
2507 }
2508
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 @Override
2510 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2511 synchronized (mGlobalLock) {
2512 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2513 }
2514 }
2515
2516 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2518 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2519 }
2520
2521 @Override
2522 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2523 @WindowConfiguration.ActivityType int ignoreActivityType,
2524 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2525 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002526 final int callingPid = Binder.getCallingPid();
2527 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002528 final int[] profileIds = getUserManager().getProfileIds(
2529 UserHandle.getUserId(callingUid), true);
2530 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2531 for (int i = 0; i < profileIds.length; i++) {
2532 callingProfileIds.add(profileIds[i]);
2533 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002534 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2535
2536 synchronized (mGlobalLock) {
2537 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2538
Nicholas Sauer0259e532019-08-30 08:24:55 -07002539 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002540 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002541 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 }
2543
2544 return list;
2545 }
2546
2547 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2549 synchronized (mGlobalLock) {
2550 final long origId = Binder.clearCallingIdentity();
2551 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2552 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002553 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 }
2555 Binder.restoreCallingIdentity(origId);
2556 }
2557 }
2558
2559 @Override
2560 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 ActivityStack stack = ActivityRecord.getStackLocked(token);
2563 if (stack != null) {
2564 return stack.willActivityBeVisibleLocked(token);
2565 }
2566 return false;
2567 }
2568 }
2569
2570 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 synchronized (mGlobalLock) {
2574 final long ident = Binder.clearCallingIdentity();
2575 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002576 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 if (task == null) {
2578 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2579 return;
2580 }
2581
2582 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2583 + " to stackId=" + stackId + " toTop=" + toTop);
2584
Wale Ogunwaled32da472018-11-16 07:19:28 -08002585 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 if (stack == null) {
2587 throw new IllegalStateException(
2588 "moveTaskToStack: No stack for stackId=" + stackId);
2589 }
2590 if (!stack.isActivityTypeStandardOrUndefined()) {
2591 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2592 + taskId + " to stack " + stackId);
2593 }
2594 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002595 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2597 }
2598 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2599 "moveTaskToStack");
2600 } finally {
2601 Binder.restoreCallingIdentity(ident);
2602 }
2603 }
2604 }
2605
2606 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002607 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2608 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609
2610 final long ident = Binder.clearCallingIdentity();
2611 try {
2612 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002613 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2614 if (stack == null) {
2615 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2616 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002618 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2619 throw new IllegalArgumentException("Stack: " + stackId
2620 + " doesn't support animated resize.");
2621 }
2622 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2623 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002624 }
2625 } finally {
2626 Binder.restoreCallingIdentity(ident);
2627 }
2628 }
2629
wilsonshih5c4cf522019-01-25 09:03:47 +08002630 @Override
2631 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2632 int animationDuration) {
2633 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2634
2635 final long ident = Binder.clearCallingIdentity();
2636 try {
2637 synchronized (mGlobalLock) {
2638 if (xOffset == 0 && yOffset == 0) {
2639 return;
2640 }
2641 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2642 if (stack == null) {
2643 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2644 return;
2645 }
2646 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2647 throw new IllegalArgumentException("Stack: " + stackId
2648 + " doesn't support animated resize.");
2649 }
2650 final Rect destBounds = new Rect();
2651 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002652 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002653 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2654 return;
2655 }
2656 destBounds.offset(xOffset, yOffset);
2657 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2658 animationDuration, false /* fromFullscreen */);
2659 }
2660 } finally {
2661 Binder.restoreCallingIdentity(ident);
2662 }
2663 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002664 /**
2665 * Moves the specified task to the primary-split-screen stack.
2666 *
2667 * @param taskId Id of task to move.
2668 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2669 * exist already. See
2670 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2671 * and
2672 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2673 * @param toTop If the task and stack should be moved to the top.
2674 * @param animate Whether we should play an animation for the moving the task.
2675 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2676 * stack. Pass {@code null} to use default bounds.
2677 * @param showRecents If the recents activity should be shown on the other side of the task
2678 * going into split-screen mode.
2679 */
2680 @Override
2681 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2682 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002683 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 "setTaskWindowingModeSplitScreenPrimary()");
2685 synchronized (mGlobalLock) {
2686 final long ident = Binder.clearCallingIdentity();
2687 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002688 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002689 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002690 if (task == null) {
2691 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2692 return false;
2693 }
2694 if (DEBUG_STACK) Slog.d(TAG_STACK,
2695 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2696 + " to createMode=" + createMode + " toTop=" + toTop);
2697 if (!task.isActivityTypeStandardOrUndefined()) {
2698 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2699 + " non-standard task " + taskId + " to split-screen windowing mode");
2700 }
2701
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002702 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 final int windowingMode = task.getWindowingMode();
2704 final ActivityStack stack = task.getStack();
2705 if (toTop) {
2706 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2707 }
2708 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002709 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2710 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 return windowingMode != task.getWindowingMode();
2712 } finally {
2713 Binder.restoreCallingIdentity(ident);
2714 }
2715 }
2716 }
2717
2718 /**
2719 * Removes stacks in the input windowing modes from the system if they are of activity type
2720 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2721 */
2722 @Override
2723 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002724 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002725 "removeStacksInWindowingModes()");
2726
2727 synchronized (mGlobalLock) {
2728 final long ident = Binder.clearCallingIdentity();
2729 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002730 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 } finally {
2732 Binder.restoreCallingIdentity(ident);
2733 }
2734 }
2735 }
2736
2737 @Override
2738 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002739 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002740 "removeStacksWithActivityTypes()");
2741
2742 synchronized (mGlobalLock) {
2743 final long ident = Binder.clearCallingIdentity();
2744 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002745 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 } finally {
2747 Binder.restoreCallingIdentity(ident);
2748 }
2749 }
2750 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002751
2752 @Override
2753 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2754 int userId) {
2755 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2757 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 final boolean detailed = checkGetTasksPermission(
2760 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2761 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 == PackageManager.PERMISSION_GRANTED;
2763
2764 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002765 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 callingUid);
2767 }
2768 }
2769
2770 @Override
2771 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002773 long ident = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002776 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777 }
2778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782
2783 @Override
2784 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002785 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 long ident = Binder.clearCallingIdentity();
2787 try {
2788 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002789 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 }
2791 } finally {
2792 Binder.restoreCallingIdentity(ident);
2793 }
2794 }
2795
2796 @Override
2797 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002798 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002799 final long callingUid = Binder.getCallingUid();
2800 final long origId = Binder.clearCallingIdentity();
2801 try {
2802 synchronized (mGlobalLock) {
2803 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002804 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2806 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2807 }
2808 } finally {
2809 Binder.restoreCallingIdentity(origId);
2810 }
2811 }
2812
2813 @Override
2814 public void startLockTaskModeByToken(IBinder token) {
2815 synchronized (mGlobalLock) {
2816 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2817 if (r == null) {
2818 return;
2819 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002820 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 }
2823
2824 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002825 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002826 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 // This makes inner call to look as if it was initiated by system.
2828 long ident = Binder.clearCallingIdentity();
2829 try {
2830 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002831 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002832 MATCH_TASK_IN_STACKS_ONLY);
2833 if (task == null) {
2834 return;
2835 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836
2837 // When starting lock task mode the stack must be in front and focused
2838 task.getStack().moveToFront("startSystemLockTaskMode");
2839 startLockTaskModeLocked(task, true /* isSystemCaller */);
2840 }
2841 } finally {
2842 Binder.restoreCallingIdentity(ident);
2843 }
2844 }
2845
2846 @Override
2847 public void stopLockTaskModeByToken(IBinder token) {
2848 synchronized (mGlobalLock) {
2849 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2850 if (r == null) {
2851 return;
2852 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002853 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 }
2855 }
2856
2857 /**
2858 * This API should be called by SystemUI only when user perform certain action to dismiss
2859 * lock task mode. We should only dismiss pinned lock task mode in this case.
2860 */
2861 @Override
2862 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002863 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2865 }
2866
2867 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2868 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2869 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2870 return;
2871 }
2872
Wale Ogunwaled32da472018-11-16 07:19:28 -08002873 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 if (stack == null || task != stack.topTask()) {
2875 throw new IllegalArgumentException("Invalid task, not in foreground");
2876 }
2877
2878 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2879 // system or a specific app.
2880 // * System-initiated requests will only start the pinned mode (screen pinning)
2881 // * App-initiated requests
2882 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2883 // - will start the pinned mode, otherwise
2884 final int callingUid = Binder.getCallingUid();
2885 long ident = Binder.clearCallingIdentity();
2886 try {
2887 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002888 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002889
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002890 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 } finally {
2892 Binder.restoreCallingIdentity(ident);
2893 }
2894 }
2895
2896 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2897 final int callingUid = Binder.getCallingUid();
2898 long ident = Binder.clearCallingIdentity();
2899 try {
2900 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002901 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2904 // task and jumping straight into a call in the case of emergency call back.
2905 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2906 if (tm != null) {
2907 tm.showInCallScreen(false);
2908 }
2909 } finally {
2910 Binder.restoreCallingIdentity(ident);
2911 }
2912 }
2913
2914 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002915 public void updateLockTaskPackages(int userId, String[] packages) {
2916 final int callingUid = Binder.getCallingUid();
2917 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2918 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2919 "updateLockTaskPackages()");
2920 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002921 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002922 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2923 + Arrays.toString(packages));
2924 getLockTaskController().updateLockTaskPackages(userId, packages);
2925 }
2926 }
2927
2928 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 public boolean isInLockTaskMode() {
2930 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2931 }
2932
2933 @Override
2934 public int getLockTaskModeState() {
2935 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002936 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 }
2938 }
2939
2940 @Override
2941 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2942 synchronized (mGlobalLock) {
2943 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2944 if (r != null) {
2945 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002946 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002948 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 }
2950 }
2951 }
2952
2953 @Override
2954 public Bundle getActivityOptions(IBinder token) {
2955 final long origId = Binder.clearCallingIdentity();
2956 try {
2957 synchronized (mGlobalLock) {
2958 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2959 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002960 final ActivityOptions activityOptions = r.takeOptionsLocked(
2961 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002962 return activityOptions == null ? null : activityOptions.toBundle();
2963 }
2964 return null;
2965 }
2966 } finally {
2967 Binder.restoreCallingIdentity(origId);
2968 }
2969 }
2970
2971 @Override
2972 public List<IBinder> getAppTasks(String callingPackage) {
2973 int callingUid = Binder.getCallingUid();
2974 long ident = Binder.clearCallingIdentity();
2975 try {
2976 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002977 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 }
2979 } finally {
2980 Binder.restoreCallingIdentity(ident);
2981 }
2982 }
2983
2984 @Override
2985 public void finishVoiceTask(IVoiceInteractionSession session) {
2986 synchronized (mGlobalLock) {
2987 final long origId = Binder.clearCallingIdentity();
2988 try {
2989 // TODO: VI Consider treating local voice interactions and voice tasks
2990 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002991 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 } finally {
2993 Binder.restoreCallingIdentity(origId);
2994 }
2995 }
2996
2997 }
2998
2999 @Override
3000 public boolean isTopOfTask(IBinder token) {
3001 synchronized (mGlobalLock) {
3002 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003003 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 }
3005 }
3006
3007 @Override
3008 public void notifyLaunchTaskBehindComplete(IBinder token) {
3009 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3010 }
3011
3012 @Override
3013 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003014 mH.post(() -> {
3015 synchronized (mGlobalLock) {
3016 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003017 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003018 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003019 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003020 } catch (RemoteException e) {
3021 }
3022 }
3023 }
3024
3025 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003026 }
3027
3028 /** Called from an app when assist data is ready. */
3029 @Override
3030 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3031 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003032 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 synchronized (pae) {
3034 pae.result = extras;
3035 pae.structure = structure;
3036 pae.content = content;
3037 if (referrer != null) {
3038 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3039 }
3040 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003041 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003042 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003043 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 structure.setHomeActivity(pae.isHome);
3045 }
3046 pae.haveResult = true;
3047 pae.notifyAll();
3048 if (pae.intent == null && pae.receiver == null) {
3049 // Caller is just waiting for the result.
3050 return;
3051 }
3052 }
3053 // We are now ready to launch the assist activity.
3054 IAssistDataReceiver sendReceiver = null;
3055 Bundle sendBundle = null;
3056 synchronized (mGlobalLock) {
3057 buildAssistBundleLocked(pae, extras);
3058 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003059 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 if (!exists) {
3061 // Timed out.
3062 return;
3063 }
3064
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003065 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 // Caller wants result sent back to them.
3067 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003068 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003069 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003070 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3071 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3073 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3074 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3075 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3076 }
3077 }
3078 if (sendReceiver != null) {
3079 try {
3080 sendReceiver.onHandleAssistData(sendBundle);
3081 } catch (RemoteException e) {
3082 }
3083 return;
3084 }
3085
3086 final long ident = Binder.clearCallingIdentity();
3087 try {
3088 if (TextUtils.equals(pae.intent.getAction(),
3089 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003090 // Start voice interaction through VoiceInteractionManagerService.
3091 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3092 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003093 } else {
3094 pae.intent.replaceExtras(pae.extras);
3095 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3096 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3097 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003098 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099
3100 try {
3101 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3102 } catch (ActivityNotFoundException e) {
3103 Slog.w(TAG, "No activity to handle assist action.", e);
3104 }
3105 }
3106 } finally {
3107 Binder.restoreCallingIdentity(ident);
3108 }
3109 }
3110
3111 @Override
3112 public int addAppTask(IBinder activityToken, Intent intent,
3113 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3114 final int callingUid = Binder.getCallingUid();
3115 final long callingIdent = Binder.clearCallingIdentity();
3116
3117 try {
3118 synchronized (mGlobalLock) {
3119 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3120 if (r == null) {
3121 throw new IllegalArgumentException("Activity does not exist; token="
3122 + activityToken);
3123 }
3124 ComponentName comp = intent.getComponent();
3125 if (comp == null) {
3126 throw new IllegalArgumentException("Intent " + intent
3127 + " must specify explicit component");
3128 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003129 if (thumbnail.getWidth() != mThumbnailWidth
3130 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131 throw new IllegalArgumentException("Bad thumbnail size: got "
3132 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003133 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003134 }
3135 if (intent.getSelector() != null) {
3136 intent.setSelector(null);
3137 }
3138 if (intent.getSourceBounds() != null) {
3139 intent.setSourceBounds(null);
3140 }
3141 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3142 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3143 // The caller has added this as an auto-remove task... that makes no
3144 // sense, so turn off auto-remove.
3145 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3146 }
3147 }
3148 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3149 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3150 if (ainfo.applicationInfo.uid != callingUid) {
3151 throw new SecurityException(
3152 "Can't add task for another application: target uid="
3153 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3154 }
3155
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003156 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003158 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003160 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003162 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003163 return INVALID_TASK_ID;
3164 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003165 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166
3167 // TODO: Send the thumbnail to WM to store it.
3168
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003169 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 }
3171 } finally {
3172 Binder.restoreCallingIdentity(callingIdent);
3173 }
3174 }
3175
3176 @Override
3177 public Point getAppTaskThumbnailSize() {
3178 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003179 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 }
3181 }
3182
3183 @Override
3184 public void setTaskResizeable(int taskId, int resizeableMode) {
3185 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003186 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3188 if (task == null) {
3189 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3190 return;
3191 }
3192 task.setResizeMode(resizeableMode);
3193 }
3194 }
3195
3196 @Override
3197 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003198 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003199 long ident = Binder.clearCallingIdentity();
3200 try {
3201 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003202 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003203 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 if (task == null) {
3205 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3206 return;
3207 }
3208 // Place the task in the right stack if it isn't there already based on
3209 // the requested bounds.
3210 // The stack transition logic is:
3211 // - a null bounds on a freeform task moves that task to fullscreen
3212 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3213 // that task to freeform
3214 // - otherwise the task is not moved
3215 ActivityStack stack = task.getStack();
3216 if (!task.getWindowConfiguration().canResizeTask()) {
3217 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3218 }
3219 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3220 stack = stack.getDisplay().getOrCreateStack(
3221 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3222 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3223 stack = stack.getDisplay().getOrCreateStack(
3224 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3225 }
3226
3227 // Reparent the task to the right stack if necessary
3228 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3229 if (stack != task.getStack()) {
3230 // Defer resume until the task is resized below
3231 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3232 DEFER_RESUME, "resizeTask");
3233 preserveWindow = false;
3234 }
3235
3236 // After reparenting (which only resizes the task to the stack bounds), resize the
3237 // task to the actual bounds provided
3238 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3239 }
3240 } finally {
3241 Binder.restoreCallingIdentity(ident);
3242 }
3243 }
3244
Evan Roskyddedfd42019-10-04 13:38:38 -07003245 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3246 WindowContainerTransaction.Change change) {
3247 if (!(container instanceof TaskRecord)) {
3248 throw new RuntimeException("Invalid token in task transaction");
3249 }
3250 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3251 // masks here.
3252 int configMask = change.getConfigSetMask();
3253 int windowMask = change.getWindowSetMask();
3254 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3255 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3256 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3257 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3258 c.setTo(change.getConfiguration(), configMask, windowMask);
3259 container.onRequestedOverrideConfigurationChanged(c);
3260 }
3261
3262 @Override
3263 public void applyContainerTransaction(WindowContainerTransaction t) {
3264 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3265 long ident = Binder.clearCallingIdentity();
3266 try {
3267 if (t == null) {
3268 return;
3269 }
3270 synchronized (mGlobalLock) {
3271 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3272 t.getChanges().entrySet().iterator();
3273 while (entries.hasNext()) {
3274 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3275 entries.next();
3276 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3277 entry.getKey()).getContainer();
3278 sanitizeAndApplyConfigChange(cc, entry.getValue());
3279 }
3280 }
3281 } finally {
3282 Binder.restoreCallingIdentity(ident);
3283 }
3284 }
3285
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003286 @Override
3287 public boolean releaseActivityInstance(IBinder token) {
3288 synchronized (mGlobalLock) {
3289 final long origId = Binder.clearCallingIdentity();
3290 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003291 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3292 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 return false;
3294 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003295 r.destroyImmediately(true /* removeFromApp */, "app-req");
3296 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 } finally {
3298 Binder.restoreCallingIdentity(origId);
3299 }
3300 }
3301 }
3302
3303 @Override
3304 public void releaseSomeActivities(IApplicationThread appInt) {
3305 synchronized (mGlobalLock) {
3306 final long origId = Binder.clearCallingIdentity();
3307 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003308 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003309 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 } finally {
3311 Binder.restoreCallingIdentity(origId);
3312 }
3313 }
3314 }
3315
3316 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003317 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003318 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 != PackageManager.PERMISSION_GRANTED) {
3320 throw new SecurityException("Requires permission "
3321 + android.Manifest.permission.DEVICE_POWER);
3322 }
3323
3324 synchronized (mGlobalLock) {
3325 long ident = Binder.clearCallingIdentity();
3326 if (mKeyguardShown != keyguardShowing) {
3327 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003328 final Message msg = PooledLambda.obtainMessage(
3329 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3330 keyguardShowing);
3331 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 }
3333 try {
wilsonshih177261f2019-02-22 12:02:18 +08003334 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003335 } finally {
3336 Binder.restoreCallingIdentity(ident);
3337 }
3338 }
3339
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003340 mH.post(() -> {
3341 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3342 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3343 }
3344 });
3345 }
3346
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003347 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003348 mH.post(() -> {
3349 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3350 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3351 }
3352 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 }
3354
3355 @Override
3356 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003357 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3358 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359
3360 final File passedIconFile = new File(filePath);
3361 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3362 passedIconFile.getName());
3363 if (!legitIconFile.getPath().equals(filePath)
3364 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3365 throw new IllegalArgumentException("Bad file path: " + filePath
3366 + " passed for userId " + userId);
3367 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003368 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 }
3370
3371 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003373 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 synchronized (mGlobalLock) {
3375 final long ident = Binder.clearCallingIdentity();
3376 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003377 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 if (stack == null) {
3379 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3380 return;
3381 }
3382 if (!stack.isActivityTypeStandardOrUndefined()) {
3383 throw new IllegalArgumentException(
3384 "Removing non-standard stack is not allowed.");
3385 }
3386 mStackSupervisor.removeStack(stack);
3387 } finally {
3388 Binder.restoreCallingIdentity(ident);
3389 }
3390 }
3391 }
3392
3393 @Override
3394 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003395 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396
3397 synchronized (mGlobalLock) {
3398 final long ident = Binder.clearCallingIdentity();
3399 try {
3400 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3401 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003402 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003403 } finally {
3404 Binder.restoreCallingIdentity(ident);
3405 }
3406 }
3407 }
3408
3409 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003410 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411 synchronized (mGlobalLock) {
3412 long ident = Binder.clearCallingIdentity();
3413 try {
3414 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3415 if (r == null) {
3416 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003417 "toggleFreeformWindowingMode: No activity record matching token="
3418 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 }
3420
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003421 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003422 if (stack == null) {
3423 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3424 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 }
3426
Yunfan Chend967af82019-01-17 18:30:18 +09003427 if (!stack.inFreeformWindowingMode()
3428 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3429 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3430 + "toggle between fullscreen and freeform.");
3431 }
3432
3433 if (stack.inFreeformWindowingMode()) {
3434 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003435 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003436 throw new IllegalStateException("Size-compat windows are currently not"
3437 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003438 } else if (stack.getParent().inFreeformWindowingMode()) {
3439 // If the window is on a freeform display, set it to undefined. It will be
3440 // resolved to freeform and it can adjust windowing mode when the display mode
3441 // changes in runtime.
3442 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003443 } else {
3444 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3445 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 } finally {
3447 Binder.restoreCallingIdentity(ident);
3448 }
3449 }
3450 }
3451
3452 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3453 @Override
3454 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003457 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003458 }
3459
3460 /** Unregister a task stack listener so that it stops receiving callbacks. */
3461 @Override
3462 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003463 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003465 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 }
3467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 @Override
3469 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3470 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3471 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3472 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3473 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3474 }
3475
3476 @Override
3477 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3478 IBinder activityToken, int flags) {
3479 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3480 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3481 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3482 }
3483
3484 @Override
3485 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3486 Bundle args) {
3487 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3488 true /* focused */, true /* newSessionId */, userHandle, args,
3489 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3490 }
3491
3492 @Override
3493 public Bundle getAssistContextExtras(int requestType) {
3494 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3495 null, null, true /* focused */, true /* newSessionId */,
3496 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3497 if (pae == null) {
3498 return null;
3499 }
3500 synchronized (pae) {
3501 while (!pae.haveResult) {
3502 try {
3503 pae.wait();
3504 } catch (InterruptedException e) {
3505 }
3506 }
3507 }
3508 synchronized (mGlobalLock) {
3509 buildAssistBundleLocked(pae, pae.result);
3510 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003511 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 }
3513 return pae.extras;
3514 }
3515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 /**
3517 * Binder IPC calls go through the public entry point.
3518 * This can be called with or without the global lock held.
3519 */
3520 private static int checkCallingPermission(String permission) {
3521 return checkPermission(
3522 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3523 }
3524
3525 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003526 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3528 mAmInternal.enforceCallingPermission(permission, func);
3529 }
3530 }
3531
3532 @VisibleForTesting
3533 int checkGetTasksPermission(String permission, int pid, int uid) {
3534 return checkPermission(permission, pid, uid);
3535 }
3536
3537 static int checkPermission(String permission, int pid, int uid) {
3538 if (permission == null) {
3539 return PackageManager.PERMISSION_DENIED;
3540 }
3541 return checkComponentPermission(permission, pid, uid, -1, true);
3542 }
3543
Wale Ogunwale214f3482018-10-04 11:00:47 -07003544 public static int checkComponentPermission(String permission, int pid, int uid,
3545 int owningUid, boolean exported) {
3546 return ActivityManagerService.checkComponentPermission(
3547 permission, pid, uid, owningUid, exported);
3548 }
3549
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003550 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3551 if (getRecentTasks().isCallerRecents(callingUid)) {
3552 // Always allow the recents component to get tasks
3553 return true;
3554 }
3555
3556 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3557 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3558 if (!allowed) {
3559 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3560 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3561 // Temporary compatibility: some existing apps on the system image may
3562 // still be requesting the old permission and not switched to the new
3563 // one; if so, we'll still allow them full access. This means we need
3564 // to see if they are holding the old permission and are a system app.
3565 try {
3566 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3567 allowed = true;
3568 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3569 + " is using old GET_TASKS but privileged; allowing");
3570 }
3571 } catch (RemoteException e) {
3572 }
3573 }
3574 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3575 + " does not hold REAL_GET_TASKS; limiting output");
3576 }
3577 return allowed;
3578 }
3579
Nicholas Sauer0259e532019-08-30 08:24:55 -07003580 boolean isCrossUserAllowed(int pid, int uid) {
3581 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3582 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3583 }
3584
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003585 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3586 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3587 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3588 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 "enqueueAssistContext()");
3591
3592 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003593 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 if (activity == null) {
3595 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3596 return null;
3597 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003598 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3600 return null;
3601 }
3602 if (focused) {
3603 if (activityToken != null) {
3604 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3605 if (activity != caller) {
3606 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3607 + " is not current top " + activity);
3608 return null;
3609 }
3610 }
3611 } else {
3612 activity = ActivityRecord.forTokenLocked(activityToken);
3613 if (activity == null) {
3614 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3615 + " couldn't be found");
3616 return null;
3617 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003618 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003619 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3620 return null;
3621 }
3622 }
3623
3624 PendingAssistExtras pae;
3625 Bundle extras = new Bundle();
3626 if (args != null) {
3627 extras.putAll(args);
3628 }
3629 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003630 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003631
3632 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3633 userHandle);
3634 pae.isHome = activity.isActivityTypeHome();
3635
3636 // Increment the sessionId if necessary
3637 if (newSessionId) {
3638 mViSessionId++;
3639 }
3640 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003641 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3642 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003643 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003644 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 } catch (RemoteException e) {
3646 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3647 return null;
3648 }
3649 return pae;
3650 }
3651 }
3652
3653 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3654 if (result != null) {
3655 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3656 }
3657 if (pae.hint != null) {
3658 pae.extras.putBoolean(pae.hint, true);
3659 }
3660 }
3661
3662 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3663 IAssistDataReceiver receiver;
3664 synchronized (mGlobalLock) {
3665 mPendingAssistExtras.remove(pae);
3666 receiver = pae.receiver;
3667 }
3668 if (receiver != null) {
3669 // Caller wants result sent back to them.
3670 Bundle sendBundle = new Bundle();
3671 // At least return the receiver extras
3672 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3673 try {
3674 pae.receiver.onHandleAssistData(sendBundle);
3675 } catch (RemoteException e) {
3676 }
3677 }
3678 }
3679
3680 public class PendingAssistExtras extends Binder implements Runnable {
3681 public final ActivityRecord activity;
3682 public boolean isHome;
3683 public final Bundle extras;
3684 public final Intent intent;
3685 public final String hint;
3686 public final IAssistDataReceiver receiver;
3687 public final int userHandle;
3688 public boolean haveResult = false;
3689 public Bundle result = null;
3690 public AssistStructure structure = null;
3691 public AssistContent content = null;
3692 public Bundle receiverExtras;
3693
3694 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3695 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3696 int _userHandle) {
3697 activity = _activity;
3698 extras = _extras;
3699 intent = _intent;
3700 hint = _hint;
3701 receiver = _receiver;
3702 receiverExtras = _receiverExtras;
3703 userHandle = _userHandle;
3704 }
3705
3706 @Override
3707 public void run() {
3708 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3709 synchronized (this) {
3710 haveResult = true;
3711 notifyAll();
3712 }
3713 pendingAssistExtrasTimedOut(this);
3714 }
3715 }
3716
3717 @Override
3718 public boolean isAssistDataAllowedOnCurrentActivity() {
3719 int userId;
3720 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003721 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003722 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3723 return false;
3724 }
3725
3726 final ActivityRecord activity = focusedStack.getTopActivity();
3727 if (activity == null) {
3728 return false;
3729 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003730 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003731 }
3732 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3733 }
3734
3735 @Override
3736 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3737 long ident = Binder.clearCallingIdentity();
3738 try {
3739 synchronized (mGlobalLock) {
3740 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003741 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 if (top != caller) {
3743 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3744 + " is not current top " + top);
3745 return false;
3746 }
3747 if (!top.nowVisible) {
3748 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3749 + " is not visible");
3750 return false;
3751 }
3752 }
3753 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3754 token);
3755 } finally {
3756 Binder.restoreCallingIdentity(ident);
3757 }
3758 }
3759
3760 @Override
3761 public boolean isRootVoiceInteraction(IBinder token) {
3762 synchronized (mGlobalLock) {
3763 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3764 if (r == null) {
3765 return false;
3766 }
3767 return r.rootVoiceInteraction;
3768 }
3769 }
3770
Wale Ogunwalef6733932018-06-27 05:14:34 -07003771 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3772 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3773 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3774 if (activityToCallback == null) return;
3775 activityToCallback.setVoiceSessionLocked(voiceSession);
3776
3777 // Inform the activity
3778 try {
3779 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3780 voiceInteractor);
3781 long token = Binder.clearCallingIdentity();
3782 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003783 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003784 } finally {
3785 Binder.restoreCallingIdentity(token);
3786 }
3787 // TODO: VI Should we cache the activity so that it's easier to find later
3788 // rather than scan through all the stacks and activities?
3789 } catch (RemoteException re) {
3790 activityToCallback.clearVoiceSessionLocked();
3791 // TODO: VI Should this terminate the voice session?
3792 }
3793 }
3794
3795 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3796 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3797 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3798 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3799 boolean wasRunningVoice = mRunningVoice != null;
3800 mRunningVoice = session;
3801 if (!wasRunningVoice) {
3802 mVoiceWakeLock.acquire();
3803 updateSleepIfNeededLocked();
3804 }
3805 }
3806 }
3807
3808 void finishRunningVoiceLocked() {
3809 if (mRunningVoice != null) {
3810 mRunningVoice = null;
3811 mVoiceWakeLock.release();
3812 updateSleepIfNeededLocked();
3813 }
3814 }
3815
3816 @Override
3817 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3818 synchronized (mGlobalLock) {
3819 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3820 if (keepAwake) {
3821 mVoiceWakeLock.acquire();
3822 } else {
3823 mVoiceWakeLock.release();
3824 }
3825 }
3826 }
3827 }
3828
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 @Override
3830 public ComponentName getActivityClassForToken(IBinder token) {
3831 synchronized (mGlobalLock) {
3832 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3833 if (r == null) {
3834 return null;
3835 }
3836 return r.intent.getComponent();
3837 }
3838 }
3839
3840 @Override
3841 public String getPackageForToken(IBinder token) {
3842 synchronized (mGlobalLock) {
3843 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3844 if (r == null) {
3845 return null;
3846 }
3847 return r.packageName;
3848 }
3849 }
3850
3851 @Override
3852 public void showLockTaskEscapeMessage(IBinder token) {
3853 synchronized (mGlobalLock) {
3854 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3855 if (r == null) {
3856 return;
3857 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003858 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003859 }
3860 }
3861
3862 @Override
3863 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003864 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003865 final long token = Binder.clearCallingIdentity();
3866 try {
3867 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003868 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003869 }
3870 } finally {
3871 Binder.restoreCallingIdentity(token);
3872 }
3873 }
3874
3875 /**
3876 * Try to place task to provided position. The final position might be different depending on
3877 * current user and stacks state. The task will be moved to target stack if it's currently in
3878 * different stack.
3879 */
3880 @Override
3881 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003882 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003883 synchronized (mGlobalLock) {
3884 long ident = Binder.clearCallingIdentity();
3885 try {
3886 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3887 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003888 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 if (task == null) {
3890 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3891 + taskId);
3892 }
3893
Wale Ogunwaled32da472018-11-16 07:19:28 -08003894 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895
3896 if (stack == null) {
3897 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3898 + stackId);
3899 }
3900 if (!stack.isActivityTypeStandardOrUndefined()) {
3901 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3902 + " the position of task " + taskId + " in/to non-standard stack");
3903 }
3904
3905 // TODO: Have the callers of this API call a separate reparent method if that is
3906 // what they intended to do vs. having this method also do reparenting.
3907 if (task.getStack() == stack) {
3908 // Change position in current stack.
3909 stack.positionChildAt(task, position);
3910 } else {
3911 // Reparent to new stack.
3912 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3913 !DEFER_RESUME, "positionTaskInStack");
3914 }
3915 } finally {
3916 Binder.restoreCallingIdentity(ident);
3917 }
3918 }
3919 }
3920
3921 @Override
3922 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3923 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3924 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003925 + Arrays.toString(horizontalSizeConfiguration) + " "
3926 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 synchronized (mGlobalLock) {
3928 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3929 if (record == null) {
3930 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3931 + "found for: " + token);
3932 }
3933 record.setSizeConfigurations(horizontalSizeConfiguration,
3934 verticalSizeConfigurations, smallestSizeConfigurations);
3935 }
3936 }
3937
3938 /**
3939 * Dismisses split-screen multi-window mode.
3940 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3941 */
3942 @Override
3943 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003944 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3946 final long ident = Binder.clearCallingIdentity();
3947 try {
3948 synchronized (mGlobalLock) {
3949 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003950 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 if (stack == null) {
3952 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3953 return;
3954 }
3955
3956 if (toTop) {
3957 // Caller wants the current split-screen primary stack to be the top stack after
3958 // it goes fullscreen, so move it to the front.
3959 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003960 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003962 // stack after it goes fullscreen, so we move the focus to the top-most
3963 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3965 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3966 if (otherStack != null) {
3967 otherStack.moveToFront("dismissSplitScreenMode_other");
3968 }
3969 }
3970
Evan Rosky10475742018-09-05 19:02:48 -07003971 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003972 }
3973 } finally {
3974 Binder.restoreCallingIdentity(ident);
3975 }
3976 }
3977
3978 /**
3979 * Dismisses Pip
3980 * @param animate True if the dismissal should be animated.
3981 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3982 * default animation duration should be used.
3983 */
3984 @Override
3985 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003986 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 final long ident = Binder.clearCallingIdentity();
3988 try {
3989 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003990 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003991 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 if (stack == null) {
3993 Slog.w(TAG, "dismissPip: pinned stack not found.");
3994 return;
3995 }
3996 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3997 throw new IllegalArgumentException("Stack: " + stack
3998 + " doesn't support animated resize.");
3999 }
4000 if (animate) {
4001 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4002 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4003 } else {
4004 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4005 }
4006 }
4007 } finally {
4008 Binder.restoreCallingIdentity(ident);
4009 }
4010 }
4011
4012 @Override
4013 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004014 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 synchronized (mGlobalLock) {
4016 mSuppressResizeConfigChanges = suppress;
4017 }
4018 }
4019
4020 /**
4021 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4022 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4023 * activity and clearing the task at the same time.
4024 */
4025 @Override
4026 // TODO: API should just be about changing windowing modes...
4027 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004028 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 "moveTasksToFullscreenStack()");
4030 synchronized (mGlobalLock) {
4031 final long origId = Binder.clearCallingIdentity();
4032 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004033 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004034 if (stack != null){
4035 if (!stack.isActivityTypeStandardOrUndefined()) {
4036 throw new IllegalArgumentException(
4037 "You can't move tasks from non-standard stacks.");
4038 }
4039 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4040 }
4041 } finally {
4042 Binder.restoreCallingIdentity(origId);
4043 }
4044 }
4045 }
4046
4047 /**
4048 * Moves the top activity in the input stackId to the pinned stack.
4049 *
4050 * @param stackId Id of stack to move the top activity to pinned stack.
4051 * @param bounds Bounds to use for pinned stack.
4052 *
4053 * @return True if the top activity of the input stack was successfully moved to the pinned
4054 * stack.
4055 */
4056 @Override
4057 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004058 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 "moveTopActivityToPinnedStack()");
4060 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004061 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4063 + "Device doesn't support picture-in-picture mode");
4064 }
4065
4066 long ident = Binder.clearCallingIdentity();
4067 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004068 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 } finally {
4070 Binder.restoreCallingIdentity(ident);
4071 }
4072 }
4073 }
4074
4075 @Override
4076 public boolean isInMultiWindowMode(IBinder token) {
4077 final long origId = Binder.clearCallingIdentity();
4078 try {
4079 synchronized (mGlobalLock) {
4080 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4081 if (r == null) {
4082 return false;
4083 }
4084 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4085 return r.inMultiWindowMode();
4086 }
4087 } finally {
4088 Binder.restoreCallingIdentity(origId);
4089 }
4090 }
4091
4092 @Override
4093 public boolean isInPictureInPictureMode(IBinder token) {
4094 final long origId = Binder.clearCallingIdentity();
4095 try {
4096 synchronized (mGlobalLock) {
4097 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(origId);
4101 }
4102 }
4103
4104 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004105 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4106 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 return false;
4108 }
4109
4110 // If we are animating to fullscreen then we have already dispatched the PIP mode
4111 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004112 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4113 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 }
4115
4116 @Override
4117 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4118 final long origId = Binder.clearCallingIdentity();
4119 try {
4120 synchronized (mGlobalLock) {
4121 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4122 "enterPictureInPictureMode", token, params);
4123
4124 // If the activity is already in picture in picture mode, then just return early
4125 if (isInPictureInPictureMode(r)) {
4126 return true;
4127 }
4128
4129 // Activity supports picture-in-picture, now check that we can enter PiP at this
4130 // point, if it is
4131 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4132 false /* beforeStopping */)) {
4133 return false;
4134 }
4135
4136 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004137 synchronized (mGlobalLock) {
4138 // Only update the saved args from the args that are set
4139 r.pictureInPictureArgs.copyOnlySet(params);
4140 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4141 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4142 // Adjust the source bounds by the insets for the transition down
4143 final Rect sourceBounds = new Rect(
4144 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004145 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004146 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004147 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004148 stack.setPictureInPictureAspectRatio(aspectRatio);
4149 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004150 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4151 r.info.applicationInfo.uid, r.shortComponentName,
4152 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004153 logPictureInPictureArgs(params);
4154 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 };
4156
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004157 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 // If the keyguard is showing or occluded, then try and dismiss it before
4159 // entering picture-in-picture (this will prompt the user to authenticate if the
4160 // device is currently locked).
4161 dismissKeyguard(token, new KeyguardDismissCallback() {
4162 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004163 public void onDismissSucceeded() {
4164 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 }
4166 }, null /* message */);
4167 } else {
4168 // Enter picture in picture immediately otherwise
4169 enterPipRunnable.run();
4170 }
4171 return true;
4172 }
4173 } finally {
4174 Binder.restoreCallingIdentity(origId);
4175 }
4176 }
4177
4178 @Override
4179 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4180 final long origId = Binder.clearCallingIdentity();
4181 try {
4182 synchronized (mGlobalLock) {
4183 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4184 "setPictureInPictureParams", token, params);
4185
4186 // Only update the saved args from the args that are set
4187 r.pictureInPictureArgs.copyOnlySet(params);
4188 if (r.inPinnedWindowingMode()) {
4189 // If the activity is already in picture-in-picture, update the pinned stack now
4190 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4191 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004192 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004193 if (!stack.isAnimatingBoundsToFullscreen()) {
4194 stack.setPictureInPictureAspectRatio(
4195 r.pictureInPictureArgs.getAspectRatio());
4196 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4197 }
4198 }
4199 logPictureInPictureArgs(params);
4200 }
4201 } finally {
4202 Binder.restoreCallingIdentity(origId);
4203 }
4204 }
4205
4206 @Override
4207 public int getMaxNumPictureInPictureActions(IBinder token) {
4208 // Currently, this is a static constant, but later, we may change this to be dependent on
4209 // the context of the activity
4210 return 3;
4211 }
4212
4213 private void logPictureInPictureArgs(PictureInPictureParams params) {
4214 if (params.hasSetActions()) {
4215 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4216 params.getActions().size());
4217 }
4218 if (params.hasSetAspectRatio()) {
4219 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4220 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4221 MetricsLogger.action(lm);
4222 }
4223 }
4224
4225 /**
4226 * Checks the state of the system and the activity associated with the given {@param token} to
4227 * verify that picture-in-picture is supported for that activity.
4228 *
4229 * @return the activity record for the given {@param token} if all the checks pass.
4230 */
4231 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4232 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 throw new IllegalStateException(caller
4235 + ": Device doesn't support picture-in-picture mode.");
4236 }
4237
4238 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4239 if (r == null) {
4240 throw new IllegalStateException(caller
4241 + ": Can't find activity for token=" + token);
4242 }
4243
4244 if (!r.supportsPictureInPicture()) {
4245 throw new IllegalStateException(caller
4246 + ": Current activity does not support picture-in-picture.");
4247 }
4248
4249 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004250 && !mWindowManager.isValidPictureInPictureAspectRatio(
4251 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 final float minAspectRatio = mContext.getResources().getFloat(
4253 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4254 final float maxAspectRatio = mContext.getResources().getFloat(
4255 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4256 throw new IllegalArgumentException(String.format(caller
4257 + ": Aspect ratio is too extreme (must be between %f and %f).",
4258 minAspectRatio, maxAspectRatio));
4259 }
4260
4261 // Truncate the number of actions if necessary
4262 params.truncateActions(getMaxNumPictureInPictureActions(token));
4263
4264 return r;
4265 }
4266
4267 @Override
4268 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004269 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004270 synchronized (mGlobalLock) {
4271 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4272 if (r == null) {
4273 throw new IllegalArgumentException("Activity does not exist; token="
4274 + activityToken);
4275 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004276 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004277 }
4278 }
4279
4280 @Override
4281 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4282 Rect tempDockedTaskInsetBounds,
4283 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004284 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 long ident = Binder.clearCallingIdentity();
4286 try {
4287 synchronized (mGlobalLock) {
4288 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4289 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4290 PRESERVE_WINDOWS);
4291 }
4292 } finally {
4293 Binder.restoreCallingIdentity(ident);
4294 }
4295 }
4296
4297 @Override
4298 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 final long ident = Binder.clearCallingIdentity();
4301 try {
4302 synchronized (mGlobalLock) {
4303 mStackSupervisor.setSplitScreenResizing(resizing);
4304 }
4305 } finally {
4306 Binder.restoreCallingIdentity(ident);
4307 }
4308 }
4309
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 /**
4311 * Check that we have the features required for VR-related API calls, and throw an exception if
4312 * not.
4313 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004314 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004315 if (!mContext.getPackageManager().hasSystemFeature(
4316 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4317 throw new UnsupportedOperationException("VR mode not supported on this device!");
4318 }
4319 }
4320
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004321 @Override
4322 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004323 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324
4325 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4326
4327 ActivityRecord r;
4328 synchronized (mGlobalLock) {
4329 r = ActivityRecord.isInStackLocked(token);
4330 }
4331
4332 if (r == null) {
4333 throw new IllegalArgumentException();
4334 }
4335
4336 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004337 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004338 VrManagerInternal.NO_ERROR) {
4339 return err;
4340 }
4341
4342 // Clear the binder calling uid since this path may call moveToTask().
4343 final long callingId = Binder.clearCallingIdentity();
4344 try {
4345 synchronized (mGlobalLock) {
4346 r.requestedVrComponent = (enabled) ? packageName : null;
4347
4348 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004349 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004350 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 }
4352 return 0;
4353 }
4354 } finally {
4355 Binder.restoreCallingIdentity(callingId);
4356 }
4357 }
4358
4359 @Override
4360 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4361 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4362 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004363 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4365 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4366 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004367 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 || activity.voiceSession != null) {
4369 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4370 return;
4371 }
4372 if (activity.pendingVoiceInteractionStart) {
4373 Slog.w(TAG, "Pending start of voice interaction already.");
4374 return;
4375 }
4376 activity.pendingVoiceInteractionStart = true;
4377 }
4378 LocalServices.getService(VoiceInteractionManagerInternal.class)
4379 .startLocalVoiceInteraction(callingActivity, options);
4380 }
4381
4382 @Override
4383 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4384 LocalServices.getService(VoiceInteractionManagerInternal.class)
4385 .stopLocalVoiceInteraction(callingActivity);
4386 }
4387
4388 @Override
4389 public boolean supportsLocalVoiceInteraction() {
4390 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4391 .supportsLocalVoiceInteraction();
4392 }
4393
4394 /** Notifies all listeners when the pinned stack animation starts. */
4395 @Override
4396 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004397 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399
4400 /** Notifies all listeners when the pinned stack animation ends. */
4401 @Override
4402 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004403 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 }
4405
4406 @Override
4407 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004408 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 final long ident = Binder.clearCallingIdentity();
4410 try {
4411 synchronized (mGlobalLock) {
4412 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4413 }
4414 } finally {
4415 Binder.restoreCallingIdentity(ident);
4416 }
4417 }
4418
4419 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422
4423 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004424 if (mWindowManager == null) {
4425 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4426 return false;
4427 }
4428
4429 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004431 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 }
4433
Riddle Hsua0022cd2019-09-09 21:12:41 +08004434 mH.sendMessage(PooledLambda.obtainMessage(
4435 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4436 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437
4438 final long origId = Binder.clearCallingIdentity();
4439 try {
4440 if (values != null) {
4441 Settings.System.clearConfiguration(values);
4442 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 UserHandle.USER_NULL, false /* deferResume */,
4445 mTmpUpdateConfigurationResult);
4446 return mTmpUpdateConfigurationResult.changes != 0;
4447 } finally {
4448 Binder.restoreCallingIdentity(origId);
4449 }
4450 }
4451 }
4452
4453 @Override
4454 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4455 CharSequence message) {
4456 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4459 }
4460 final long callingId = Binder.clearCallingIdentity();
4461 try {
4462 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004463 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464 }
4465 } finally {
4466 Binder.restoreCallingIdentity(callingId);
4467 }
4468 }
4469
4470 @Override
4471 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 "cancelTaskWindowTransition()");
4474 final long ident = Binder.clearCallingIdentity();
4475 try {
4476 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004477 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004478 MATCH_TASK_IN_STACKS_ONLY);
4479 if (task == null) {
4480 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4481 return;
4482 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004483 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 }
4485 } finally {
4486 Binder.restoreCallingIdentity(ident);
4487 }
4488 }
4489
4490 @Override
4491 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004492 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 final long ident = Binder.clearCallingIdentity();
4494 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004495 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 } finally {
4497 Binder.restoreCallingIdentity(ident);
4498 }
4499 }
4500
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004501 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4502 boolean restoreFromDisk) {
4503 final TaskRecord task;
4504 synchronized (mGlobalLock) {
4505 task = mRootActivityContainer.anyTaskForId(taskId,
4506 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4507 if (task == null) {
4508 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4509 return null;
4510 }
4511 }
4512 // Don't call this while holding the lock as this operation might hit the disk.
4513 return task.getSnapshot(reducedResolution, restoreFromDisk);
4514 }
4515
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 @Override
4517 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4518 synchronized (mGlobalLock) {
4519 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4520 if (r == null) {
4521 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4522 + token);
4523 return;
4524 }
4525 final long origId = Binder.clearCallingIdentity();
4526 try {
4527 r.setDisablePreviewScreenshots(disable);
4528 } finally {
4529 Binder.restoreCallingIdentity(origId);
4530 }
4531 }
4532 }
4533
4534 /** Return the user id of the last resumed activity. */
4535 @Override
4536 public @UserIdInt
4537 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004538 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004539 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4540 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004541 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004542 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004544 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004545 }
4546 }
4547
4548 @Override
4549 public void updateLockTaskFeatures(int userId, int flags) {
4550 final int callingUid = Binder.getCallingUid();
4551 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 "updateLockTaskFeatures()");
4554 }
4555 synchronized (mGlobalLock) {
4556 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4557 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004558 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 }
4560 }
4561
4562 @Override
4563 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4564 synchronized (mGlobalLock) {
4565 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4566 if (r == null) {
4567 return;
4568 }
4569 final long origId = Binder.clearCallingIdentity();
4570 try {
4571 r.setShowWhenLocked(showWhenLocked);
4572 } finally {
4573 Binder.restoreCallingIdentity(origId);
4574 }
4575 }
4576 }
4577
4578 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004579 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4580 synchronized (mGlobalLock) {
4581 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4582 if (r == null) {
4583 return;
4584 }
4585 final long origId = Binder.clearCallingIdentity();
4586 try {
4587 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592 }
4593
4594 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4596 synchronized (mGlobalLock) {
4597 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4598 if (r == null) {
4599 return;
4600 }
4601 final long origId = Binder.clearCallingIdentity();
4602 try {
4603 r.setTurnScreenOn(turnScreenOn);
4604 } finally {
4605 Binder.restoreCallingIdentity(origId);
4606 }
4607 }
4608 }
4609
4610 @Override
4611 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004612 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004614 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 synchronized (mGlobalLock) {
4616 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4617 if (r == null) {
4618 return;
4619 }
4620 final long origId = Binder.clearCallingIdentity();
4621 try {
4622 r.registerRemoteAnimations(definition);
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627 }
4628
4629 @Override
4630 public void registerRemoteAnimationForNextActivityStart(String packageName,
4631 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004632 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004634 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 synchronized (mGlobalLock) {
4636 final long origId = Binder.clearCallingIdentity();
4637 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004638 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 packageName, adapter);
4640 } finally {
4641 Binder.restoreCallingIdentity(origId);
4642 }
4643 }
4644 }
4645
Evan Rosky966759f2019-01-15 10:33:58 -08004646 @Override
4647 public void registerRemoteAnimationsForDisplay(int displayId,
4648 RemoteAnimationDefinition definition) {
4649 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4650 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004651 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004652 synchronized (mGlobalLock) {
4653 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4654 if (display == null) {
4655 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4656 return;
4657 }
4658 final long origId = Binder.clearCallingIdentity();
4659 try {
4660 display.mDisplayContent.registerRemoteAnimations(definition);
4661 } finally {
4662 Binder.restoreCallingIdentity(origId);
4663 }
4664 }
4665 }
4666
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004667 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4668 @Override
4669 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4670 synchronized (mGlobalLock) {
4671 final long origId = Binder.clearCallingIdentity();
4672 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004673 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004674 } finally {
4675 Binder.restoreCallingIdentity(origId);
4676 }
4677 }
4678 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004679
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004680 @Override
4681 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004682 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004683 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004684 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004685 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004686 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004687 }
4688 }
4689
4690 @Override
4691 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004692 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004693 != PERMISSION_GRANTED) {
4694 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4695 + Binder.getCallingPid()
4696 + ", uid=" + Binder.getCallingUid()
4697 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4698 Slog.w(TAG, msg);
4699 throw new SecurityException(msg);
4700 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004701 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004703 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004704 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004705 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004706 }
4707 }
4708
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004709 @Override
4710 public void stopAppSwitches() {
4711 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4712 synchronized (mGlobalLock) {
4713 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004714 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004715 mDidAppSwitch = false;
4716 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4717 }
4718 }
4719
4720 @Override
4721 public void resumeAppSwitches() {
4722 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4723 synchronized (mGlobalLock) {
4724 // Note that we don't execute any pending app switches... we will
4725 // let those wait until either the timeout, or the next start
4726 // activity request.
4727 mAppSwitchesAllowedTime = 0;
4728 }
4729 }
4730
Ricky Wai906af482019-06-03 17:25:28 +01004731 long getLastStopAppSwitchesTime() {
4732 return mLastStopAppSwitchesTime;
4733 }
4734
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004735 void onStartActivitySetDidAppSwitch() {
4736 if (mDidAppSwitch) {
4737 // This is the second allowed switch since we stopped switches, so now just generally
4738 // allow switches. Use case:
4739 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4740 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4741 // anyone to switch again).
4742 mAppSwitchesAllowedTime = 0;
4743 } else {
4744 mDidAppSwitch = true;
4745 }
4746 }
4747
4748 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004749 boolean shouldDisableNonVrUiLocked() {
4750 return mVrController.shouldDisableNonVrUiLocked();
4751 }
4752
Wale Ogunwale53783742018-09-16 10:21:51 -07004753 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004754 // 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 +00004755 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004756 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004757 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4758 + " to main display for VR");
4759 mRootActivityContainer.moveStackToDisplay(
4760 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004761 }
4762 mH.post(() -> {
4763 if (!mVrController.onVrModeChanged(r)) {
4764 return;
4765 }
4766 synchronized (mGlobalLock) {
4767 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4768 mWindowManager.disableNonVrUi(disableNonVrUi);
4769 if (disableNonVrUi) {
4770 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4771 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004772 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004773 }
4774 }
4775 });
4776 }
4777
Wale Ogunwale53783742018-09-16 10:21:51 -07004778 @Override
4779 public int getPackageScreenCompatMode(String packageName) {
4780 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4781 synchronized (mGlobalLock) {
4782 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4783 }
4784 }
4785
4786 @Override
4787 public void setPackageScreenCompatMode(String packageName, int mode) {
4788 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4789 "setPackageScreenCompatMode");
4790 synchronized (mGlobalLock) {
4791 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4792 }
4793 }
4794
4795 @Override
4796 public boolean getPackageAskScreenCompat(String packageName) {
4797 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4798 synchronized (mGlobalLock) {
4799 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4800 }
4801 }
4802
4803 @Override
4804 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4805 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4806 "setPackageAskScreenCompat");
4807 synchronized (mGlobalLock) {
4808 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4809 }
4810 }
4811
Wale Ogunwale64258362018-10-16 15:13:37 -07004812 public static String relaunchReasonToString(int relaunchReason) {
4813 switch (relaunchReason) {
4814 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4815 return "window_resize";
4816 case RELAUNCH_REASON_FREE_RESIZE:
4817 return "free_resize";
4818 default:
4819 return null;
4820 }
4821 }
4822
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004823 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004824 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004825 }
4826
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004827 /** Pokes the task persister. */
4828 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4829 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4830 }
4831
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004832 boolean isKeyguardLocked() {
4833 return mKeyguardController.isKeyguardLocked();
4834 }
4835
Garfield Tan01548632018-11-27 10:15:48 -08004836 /**
4837 * Clears launch params for the given package.
4838 * @param packageNames the names of the packages of which the launch params are to be cleared
4839 */
4840 @Override
4841 public void clearLaunchParamsForPackages(List<String> packageNames) {
4842 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4843 "clearLaunchParamsForPackages");
4844 synchronized (mGlobalLock) {
4845 for (int i = 0; i < packageNames.size(); ++i) {
4846 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4847 }
4848 }
4849 }
4850
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004851 /**
4852 * Makes the display with the given id a single task instance display. I.e the display can only
4853 * contain one task.
4854 */
4855 @Override
4856 public void setDisplayToSingleTaskInstance(int displayId) {
4857 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4858 "setDisplayToSingleTaskInstance");
4859 final long origId = Binder.clearCallingIdentity();
4860 try {
4861 final ActivityDisplay display =
4862 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4863 if (display != null) {
4864 display.setDisplayToSingleTaskInstance();
4865 }
4866 } finally {
4867 Binder.restoreCallingIdentity(origId);
4868 }
4869 }
4870
Wale Ogunwale31913b52018-10-13 08:29:31 -07004871 void dumpLastANRLocked(PrintWriter pw) {
4872 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4873 if (mLastANRState == null) {
4874 pw.println(" <no ANR has occurred since boot>");
4875 } else {
4876 pw.println(mLastANRState);
4877 }
4878 }
4879
4880 void dumpLastANRTracesLocked(PrintWriter pw) {
4881 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4882
4883 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4884 if (ArrayUtils.isEmpty(files)) {
4885 pw.println(" <no ANR has occurred since boot>");
4886 return;
4887 }
4888 // Find the latest file.
4889 File latest = null;
4890 for (File f : files) {
4891 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4892 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004893 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004894 }
4895 pw.print("File: ");
4896 pw.print(latest.getName());
4897 pw.println();
4898 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4899 String line;
4900 while ((line = in.readLine()) != null) {
4901 pw.println(line);
4902 }
4903 } catch (IOException e) {
4904 pw.print("Unable to read: ");
4905 pw.print(e);
4906 pw.println();
4907 }
4908 }
4909
4910 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4911 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4912 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4913 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4914 }
4915
4916 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4917 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4918 pw.println(header);
4919
Wale Ogunwaled32da472018-11-16 07:19:28 -08004920 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004921 dumpPackage);
4922 boolean needSep = printedAnything;
4923
4924 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004925 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004926 " ResumedActivity: ");
4927 if (printed) {
4928 printedAnything = true;
4929 needSep = false;
4930 }
4931
4932 if (dumpPackage == null) {
4933 if (needSep) {
4934 pw.println();
4935 }
4936 printedAnything = true;
4937 mStackSupervisor.dump(pw, " ");
4938 }
4939
4940 if (!printedAnything) {
4941 pw.println(" (nothing)");
4942 }
4943 }
4944
4945 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004946 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004947 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004948 pw.println(" ");
4949 }
4950
4951 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4952 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4953 getActivityStartController().dump(pw, "", dumpPackage);
4954 }
4955
4956 /**
4957 * There are three things that cmd can be:
4958 * - a flattened component name that matches an existing activity
4959 * - the cmd arg isn't the flattened component name of an existing activity:
4960 * dump all activity whose component contains the cmd as a substring
4961 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004962 * <p>
4963 * The caller should not hold lock when calling this method because it will wait for the
4964 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004965 *
4966 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4967 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4968 */
4969 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4970 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4971 ArrayList<ActivityRecord> activities;
4972
4973 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004974 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004975 dumpFocusedStackOnly);
4976 }
4977
4978 if (activities.size() <= 0) {
4979 return false;
4980 }
4981
4982 String[] newArgs = new String[args.length - opti];
4983 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4984
4985 TaskRecord lastTask = null;
4986 boolean needSep = false;
4987 for (int i = activities.size() - 1; i >= 0; i--) {
4988 ActivityRecord r = activities.get(i);
4989 if (needSep) {
4990 pw.println();
4991 }
4992 needSep = true;
4993 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004994 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 if (lastTask != task) {
4996 lastTask = task;
4997 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004998 pw.print(" id="); pw.print(lastTask.mTaskId);
4999 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005000 if (dumpAll) {
5001 lastTask.dump(pw, " ");
5002 }
5003 }
5004 }
5005 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5006 }
5007 return true;
5008 }
5009
5010 /**
5011 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5012 * there is a thread associated with the activity.
5013 */
5014 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5015 final ActivityRecord r, String[] args, boolean dumpAll) {
5016 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005017 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005018 synchronized (mGlobalLock) {
5019 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5020 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5021 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005022 if (r.hasProcess()) {
5023 pw.println(r.app.getPid());
5024 appThread = r.app.getThread();
5025 } else {
5026 pw.println("(not running)");
5027 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005028 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005029 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005030 }
5031 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005032 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005033 // flush anything that is already in the PrintWriter since the thread is going
5034 // to write to the file descriptor directly
5035 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005036 try (TransferPipe tp = new TransferPipe()) {
5037 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5038 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 } catch (IOException e) {
5040 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5041 } catch (RemoteException e) {
5042 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5043 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005044 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005045 }
5046
sanryhuang498e77e2018-12-06 14:57:01 +08005047 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5048 boolean testPssMode) {
5049 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5050 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5051 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005052 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005053 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5054 st.toString());
5055 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005056 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5057 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5058 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005059 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5060 testPssMode);
5061 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005062 }
5063
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005064 int getCurrentUserId() {
5065 return mAmInternal.getCurrentUserId();
5066 }
5067
5068 private void enforceNotIsolatedCaller(String caller) {
5069 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5070 throw new SecurityException("Isolated process not allowed to call " + caller);
5071 }
5072 }
5073
Wale Ogunwalef6733932018-06-27 05:14:34 -07005074 public Configuration getConfiguration() {
5075 Configuration ci;
5076 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005077 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005078 ci.userSetLocale = false;
5079 }
5080 return ci;
5081 }
5082
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005083 /**
5084 * Current global configuration information. Contains general settings for the entire system,
5085 * also corresponds to the merged configuration of the default display.
5086 */
5087 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005088 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005089 }
5090
5091 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5092 boolean initLocale) {
5093 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5094 }
5095
5096 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5097 boolean initLocale, boolean deferResume) {
5098 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5099 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5100 UserHandle.USER_NULL, deferResume);
5101 }
5102
Wale Ogunwale59507092018-10-29 09:00:30 -07005103 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005104 final long origId = Binder.clearCallingIdentity();
5105 try {
5106 synchronized (mGlobalLock) {
5107 updateConfigurationLocked(values, null, false, true, userId,
5108 false /* deferResume */);
5109 }
5110 } finally {
5111 Binder.restoreCallingIdentity(origId);
5112 }
5113 }
5114
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005115 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5116 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5117 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5118 deferResume, null /* result */);
5119 }
5120
5121 /**
5122 * Do either or both things: (1) change the current configuration, and (2)
5123 * make sure the given activity is running with the (now) current
5124 * configuration. Returns true if the activity has been left running, or
5125 * false if <var>starting</var> is being destroyed to match the new
5126 * configuration.
5127 *
5128 * @param userId is only used when persistent parameter is set to true to persist configuration
5129 * for that particular user
5130 */
5131 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5132 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5133 ActivityTaskManagerService.UpdateConfigurationResult result) {
5134 int changes = 0;
5135 boolean kept = true;
5136
Riddle Hsua0022cd2019-09-09 21:12:41 +08005137 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005138 try {
5139 if (values != null) {
5140 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5141 deferResume);
5142 }
5143
5144 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5145 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005146 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 }
5148
5149 if (result != null) {
5150 result.changes = changes;
5151 result.activityRelaunched = !kept;
5152 }
5153 return kept;
5154 }
5155
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005156 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005157 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005158 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005159
5160 final ActivityDisplay defaultDisplay =
5161 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005163 mTempConfig.setTo(getGlobalConfiguration());
5164 final int changes = mTempConfig.updateFrom(values);
5165 if (changes == 0) {
5166 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5167 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5168 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5169 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005170 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005171 return 0;
5172 }
5173
5174 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5175 "Updating global configuration to: " + values);
5176
5177 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5178 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5179 values.colorMode,
5180 values.densityDpi,
5181 values.fontScale,
5182 values.hardKeyboardHidden,
5183 values.keyboard,
5184 values.keyboardHidden,
5185 values.mcc,
5186 values.mnc,
5187 values.navigation,
5188 values.navigationHidden,
5189 values.orientation,
5190 values.screenHeightDp,
5191 values.screenLayout,
5192 values.screenWidthDp,
5193 values.smallestScreenWidthDp,
5194 values.touchscreen,
5195 values.uiMode);
5196
5197
5198 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5199 final LocaleList locales = values.getLocales();
5200 int bestLocaleIndex = 0;
5201 if (locales.size() > 1) {
5202 if (mSupportedSystemLocales == null) {
5203 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5204 }
5205 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5206 }
5207 SystemProperties.set("persist.sys.locale",
5208 locales.get(bestLocaleIndex).toLanguageTag());
5209 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005210
5211 final Message m = PooledLambda.obtainMessage(
5212 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5213 locales.get(bestLocaleIndex));
5214 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215 }
5216
Yunfan Chen75157d72018-07-27 14:47:21 +09005217 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218
5219 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005220 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221
5222 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5223 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005224 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225
5226 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005227 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228
5229 AttributeCache ac = AttributeCache.instance();
5230 if (ac != null) {
5231 ac.updateConfiguration(mTempConfig);
5232 }
5233
5234 // Make sure all resources in our process are updated right now, so that anyone who is going
5235 // to retrieve resource values after we return will be sure to get the new ones. This is
5236 // especially important during boot, where the first config change needs to guarantee all
5237 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005238 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239
5240 // We need another copy of global config because we're scheduling some calls instead of
5241 // running them in place. We need to be sure that object we send will be handled unchanged.
5242 final Configuration configCopy = new Configuration(mTempConfig);
5243 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005244 final Message msg = PooledLambda.obtainMessage(
5245 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5246 this, userId, configCopy);
5247 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005248 }
5249
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005250 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5251 for (int i = pidMap.size() - 1; i >= 0; i--) {
5252 final int pid = pidMap.keyAt(i);
5253 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005254 if (DEBUG_CONFIGURATION) {
5255 Slog.v(TAG_CONFIGURATION, "Update process config of "
5256 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005257 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005258 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005259 }
5260
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005261 final Message msg = PooledLambda.obtainMessage(
5262 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5263 mAmInternal, changes, initLocale);
5264 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265
5266 // Override configuration of the default display duplicates global config, so we need to
5267 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005268 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5269 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005270
5271 return changes;
5272 }
5273
Riddle Hsua0022cd2019-09-09 21:12:41 +08005274 /** @see WindowSurfacePlacer#deferLayout */
5275 void deferWindowLayout() {
5276 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5277 // Reset the reasons at the first entrance because we only care about the changes in the
5278 // deferred scope.
5279 mLayoutReasons = 0;
5280 }
5281
5282 mWindowManager.mWindowPlacerLocked.deferLayout();
5283 }
5284
5285 /** @see WindowSurfacePlacer#continueLayout */
5286 void continueWindowLayout() {
5287 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5288 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5289 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5290 }
5291 }
5292
5293 /**
5294 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5295 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5296 * defer count is gone.
5297 */
5298 void addWindowLayoutReasons(@LayoutReason int reasons) {
5299 mLayoutReasons |= reasons;
5300 }
5301
Wale Ogunwalef6733932018-06-27 05:14:34 -07005302 private void updateEventDispatchingLocked(boolean booted) {
5303 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5304 }
5305
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005306 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5307 final ContentResolver resolver = mContext.getContentResolver();
5308 Settings.System.putConfigurationForUser(resolver, config, userId);
5309 }
5310
5311 private void sendLocaleToMountDaemonMsg(Locale l) {
5312 try {
5313 IBinder service = ServiceManager.getService("mount");
5314 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5315 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5316 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5317 } catch (RemoteException e) {
5318 Log.e(TAG, "Error storing locale for decryption UI", e);
5319 }
5320 }
5321
Alison Cichowlas3e340502018-08-07 17:15:01 -04005322 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5323 mStartActivitySources.remove(permissionToken);
5324 mExpiredStartAsCallerTokens.add(permissionToken);
5325 }
5326
5327 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5328 mExpiredStartAsCallerTokens.remove(permissionToken);
5329 }
5330
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005331 boolean isActivityStartsLoggingEnabled() {
5332 return mAmInternal.isActivityStartsLoggingEnabled();
5333 }
5334
Michal Karpinski8596ded2018-11-14 14:43:48 +00005335 boolean isBackgroundActivityStartsEnabled() {
5336 return mAmInternal.isBackgroundActivityStartsEnabled();
5337 }
5338
Wale Ogunwalef6733932018-06-27 05:14:34 -07005339 void enableScreenAfterBoot(boolean booted) {
5340 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5341 SystemClock.uptimeMillis());
5342 mWindowManager.enableScreenAfterBoot();
5343
5344 synchronized (mGlobalLock) {
5345 updateEventDispatchingLocked(booted);
5346 }
5347 }
5348
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005349 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5350 if (r == null || !r.hasProcess()) {
5351 return KEY_DISPATCHING_TIMEOUT_MS;
5352 }
5353 return getInputDispatchingTimeoutLocked(r.app);
5354 }
5355
5356 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005357 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005358 }
5359
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 /**
5361 * Decide based on the configuration whether we should show the ANR,
5362 * crash, etc dialogs. The idea is that if there is no affordance to
5363 * press the on-screen buttons, or the user experience would be more
5364 * greatly impacted than the crash itself, we shouldn't show the dialog.
5365 *
5366 * A thought: SystemUI might also want to get told about this, the Power
5367 * dialog / global actions also might want different behaviors.
5368 */
5369 private void updateShouldShowDialogsLocked(Configuration config) {
5370 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5371 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5372 && config.navigation == Configuration.NAVIGATION_NONAV);
5373 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5374 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5375 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5376 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5377 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5378 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5379 HIDE_ERROR_DIALOGS, 0) != 0;
5380 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5381 }
5382
5383 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5384 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5385 FONT_SCALE, 1.0f, userId);
5386
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005387 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005388 if (getGlobalConfiguration().fontScale == scaleFactor) {
5389 return;
5390 }
5391
5392 final Configuration configuration
5393 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5394 configuration.fontScale = scaleFactor;
5395 updatePersistentConfiguration(configuration, userId);
5396 }
5397 }
5398
5399 // Actually is sleeping or shutting down or whatever else in the future
5400 // is an inactive state.
5401 boolean isSleepingOrShuttingDownLocked() {
5402 return isSleepingLocked() || mShuttingDown;
5403 }
5404
5405 boolean isSleepingLocked() {
5406 return mSleeping;
5407 }
5408
Riddle Hsu16567132018-08-16 21:37:47 +08005409 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005410 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005411 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005412 if (task.isActivityTypeStandard()) {
5413 if (mCurAppTimeTracker != r.appTimeTracker) {
5414 // We are switching app tracking. Complete the current one.
5415 if (mCurAppTimeTracker != null) {
5416 mCurAppTimeTracker.stop();
5417 mH.obtainMessage(
5418 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005419 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005420 mCurAppTimeTracker = null;
5421 }
5422 if (r.appTimeTracker != null) {
5423 mCurAppTimeTracker = r.appTimeTracker;
5424 startTimeTrackingFocusedActivityLocked();
5425 }
5426 } else {
5427 startTimeTrackingFocusedActivityLocked();
5428 }
5429 } else {
5430 r.appTimeTracker = null;
5431 }
5432 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5433 // TODO: Probably not, because we don't want to resume voice on switching
5434 // back to this activity
5435 if (task.voiceInteractor != null) {
5436 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5437 } else {
5438 finishRunningVoiceLocked();
5439
5440 if (mLastResumedActivity != null) {
5441 final IVoiceInteractionSession session;
5442
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005443 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005444 if (lastResumedActivityTask != null
5445 && lastResumedActivityTask.voiceSession != null) {
5446 session = lastResumedActivityTask.voiceSession;
5447 } else {
5448 session = mLastResumedActivity.voiceSession;
5449 }
5450
5451 if (session != null) {
5452 // We had been in a voice interaction session, but now focused has
5453 // move to something different. Just finish the session, we can't
5454 // return to it and retain the proper state and synchronization with
5455 // the voice interaction service.
5456 finishVoiceTask(session);
5457 }
5458 }
5459 }
5460
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005461 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5462 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 }
5464 updateResumedAppTrace(r);
5465 mLastResumedActivity = r;
5466
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005467 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468
5469 applyUpdateLockStateLocked(r);
5470 applyUpdateVrModeLocked(r);
5471
5472 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005473 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005474 r == null ? "NULL" : r.shortComponentName,
5475 reason);
5476 }
5477
5478 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5479 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005480 final ActivityTaskManagerInternal.SleepToken token =
5481 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005482 updateSleepIfNeededLocked();
5483 return token;
5484 }
5485 }
5486
5487 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005488 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 final boolean wasSleeping = mSleeping;
5490 boolean updateOomAdj = false;
5491
5492 if (!shouldSleep) {
5493 // If wasSleeping is true, we need to wake up activity manager state from when
5494 // we started sleeping. In either case, we need to apply the sleep tokens, which
5495 // will wake up stacks or put them to sleep as appropriate.
5496 if (wasSleeping) {
5497 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005498 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5499 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 startTimeTrackingFocusedActivityLocked();
5501 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005502 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5504 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005505 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 if (wasSleeping) {
5507 updateOomAdj = true;
5508 }
5509 } else if (!mSleeping && shouldSleep) {
5510 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005511 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5512 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513 if (mCurAppTimeTracker != null) {
5514 mCurAppTimeTracker.stop();
5515 }
5516 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005517 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005518 mStackSupervisor.goingToSleepLocked();
5519 updateResumedAppTrace(null /* resumed */);
5520 updateOomAdj = true;
5521 }
5522 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005523 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005524 }
5525 }
5526
5527 void updateOomAdj() {
5528 mH.post(mAmInternal::updateOomAdj);
5529 }
5530
Wale Ogunwale53783742018-09-16 10:21:51 -07005531 void updateCpuStats() {
5532 mH.post(mAmInternal::updateCpuStats);
5533 }
5534
Hui Yu03d12402018-12-06 18:00:37 -08005535 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5536 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005537 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5538 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005539 mH.sendMessage(m);
5540 }
5541
Hui Yu03d12402018-12-06 18:00:37 -08005542 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005543 ComponentName taskRoot = null;
5544 final TaskRecord task = activity.getTaskRecord();
5545 if (task != null) {
5546 final ActivityRecord rootActivity = task.getRootActivity();
5547 if (rootActivity != null) {
5548 taskRoot = rootActivity.mActivityComponent;
5549 }
5550 }
5551
Hui Yu03d12402018-12-06 18:00:37 -08005552 final Message m = PooledLambda.obtainMessage(
5553 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005554 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005555 mH.sendMessage(m);
5556 }
5557
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005558 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5559 String hostingType) {
5560 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005561 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5562 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005563 + activity.processName);
5564 }
5565 // Post message to start process to avoid possible deadlock of calling into AMS with the
5566 // ATMS lock held.
5567 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5568 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5569 isTop, hostingType, activity.intent.getComponent());
5570 mH.sendMessage(m);
5571 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005572 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005573 }
5574 }
5575
Wale Ogunwale53783742018-09-16 10:21:51 -07005576 void setBooting(boolean booting) {
5577 mAmInternal.setBooting(booting);
5578 }
5579
5580 boolean isBooting() {
5581 return mAmInternal.isBooting();
5582 }
5583
5584 void setBooted(boolean booted) {
5585 mAmInternal.setBooted(booted);
5586 }
5587
5588 boolean isBooted() {
5589 return mAmInternal.isBooted();
5590 }
5591
5592 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5593 mH.post(() -> {
5594 if (finishBooting) {
5595 mAmInternal.finishBooting();
5596 }
5597 if (enableScreen) {
5598 mInternal.enableScreenAfterBoot(isBooted());
5599 }
5600 });
5601 }
5602
5603 void setHeavyWeightProcess(ActivityRecord root) {
5604 mHeavyWeightProcess = root.app;
5605 final Message m = PooledLambda.obtainMessage(
5606 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005607 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005608 mH.sendMessage(m);
5609 }
5610
5611 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5612 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5613 return;
5614 }
5615
5616 mHeavyWeightProcess = null;
5617 final Message m = PooledLambda.obtainMessage(
5618 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5619 proc.mUserId);
5620 mH.sendMessage(m);
5621 }
5622
5623 private void cancelHeavyWeightProcessNotification(int userId) {
5624 final INotificationManager inm = NotificationManager.getService();
5625 if (inm == null) {
5626 return;
5627 }
5628 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005629 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005630 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5631 } catch (RuntimeException e) {
5632 Slog.w(TAG, "Error canceling notification for service", e);
5633 } catch (RemoteException e) {
5634 }
5635
5636 }
5637
5638 private void postHeavyWeightProcessNotification(
5639 WindowProcessController proc, Intent intent, int userId) {
5640 if (proc == null) {
5641 return;
5642 }
5643
5644 final INotificationManager inm = NotificationManager.getService();
5645 if (inm == null) {
5646 return;
5647 }
5648
5649 try {
5650 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5651 String text = mContext.getString(R.string.heavy_weight_notification,
5652 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5653 Notification notification =
5654 new Notification.Builder(context,
5655 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5656 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5657 .setWhen(0)
5658 .setOngoing(true)
5659 .setTicker(text)
5660 .setColor(mContext.getColor(
5661 com.android.internal.R.color.system_notification_accent_color))
5662 .setContentTitle(text)
5663 .setContentText(
5664 mContext.getText(R.string.heavy_weight_notification_detail))
5665 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5666 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5667 new UserHandle(userId)))
5668 .build();
5669 try {
5670 inm.enqueueNotificationWithTag("android", "android", null,
5671 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5672 } catch (RuntimeException e) {
5673 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5674 } catch (RemoteException e) {
5675 }
5676 } catch (PackageManager.NameNotFoundException e) {
5677 Slog.w(TAG, "Unable to create context for heavy notification", e);
5678 }
5679
5680 }
5681
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005682 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5683 IBinder token, String resultWho, int requestCode, Intent[] intents,
5684 String[] resolvedTypes, int flags, Bundle bOptions) {
5685
5686 ActivityRecord activity = null;
5687 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5688 activity = ActivityRecord.isInStackLocked(token);
5689 if (activity == null) {
5690 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5691 return null;
5692 }
5693 if (activity.finishing) {
5694 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5695 return null;
5696 }
5697 }
5698
5699 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5700 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5701 bOptions);
5702 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5703 if (noCreate) {
5704 return rec;
5705 }
5706 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5707 if (activity.pendingResults == null) {
5708 activity.pendingResults = new HashSet<>();
5709 }
5710 activity.pendingResults.add(rec.ref);
5711 }
5712 return rec;
5713 }
5714
Andrii Kulian52d255c2018-07-13 11:32:19 -07005715 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005716 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005717 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005718 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5719 mCurAppTimeTracker.start(resumedActivity.packageName);
5720 }
5721 }
5722
5723 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5724 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005725 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005726 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5727 }
5728 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005729 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005730 constructResumedTraceName(resumed.packageName), 0);
5731 }
5732 mTracedResumedActivity = resumed;
5733 }
5734
5735 private String constructResumedTraceName(String packageName) {
5736 return "focused app: " + packageName;
5737 }
5738
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005739 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005740 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005741 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005742 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005743 // mainStack is null during startup.
5744 if (mainStack != null) {
5745 if (changes != 0 && starting == null) {
5746 // If the configuration changed, and the caller is not already
5747 // in the process of starting an activity, then find the top
5748 // activity to check if its configuration needs to change.
5749 starting = mainStack.topRunningActivityLocked();
5750 }
5751
5752 if (starting != null) {
5753 kept = starting.ensureActivityConfiguration(changes,
5754 false /* preserveWindow */);
5755 // And we need to make sure at this point that all other activities
5756 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005757 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005758 !PRESERVE_WINDOWS);
5759 }
5760 }
5761
5762 return kept;
5763 }
5764
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005765 void scheduleAppGcsLocked() {
5766 mH.post(() -> mAmInternal.scheduleAppGcs());
5767 }
5768
Wale Ogunwale53783742018-09-16 10:21:51 -07005769 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5770 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5771 }
5772
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005773 /**
5774 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5775 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5776 * on demand.
5777 */
5778 IPackageManager getPackageManager() {
5779 return AppGlobals.getPackageManager();
5780 }
5781
5782 PackageManagerInternal getPackageManagerInternalLocked() {
5783 if (mPmInternal == null) {
5784 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5785 }
5786 return mPmInternal;
5787 }
5788
Hai Zhangf4da9be2019-05-01 13:46:06 +08005789 PermissionPolicyInternal getPermissionPolicyInternal() {
5790 if (mPermissionPolicyInternal == null) {
5791 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5792 }
5793 return mPermissionPolicyInternal;
5794 }
5795
Wale Ogunwale008163e2018-07-23 23:11:08 -07005796 AppWarnings getAppWarningsLocked() {
5797 return mAppWarnings;
5798 }
5799
Wale Ogunwale214f3482018-10-04 11:00:47 -07005800 Intent getHomeIntent() {
5801 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5802 intent.setComponent(mTopComponent);
5803 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5804 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5805 intent.addCategory(Intent.CATEGORY_HOME);
5806 }
5807 return intent;
5808 }
5809
Chilun2ef71f72018-11-16 17:57:15 +08005810 /**
5811 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5812 * activities.
5813 *
5814 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5815 * component defined in config_secondaryHomeComponent.
5816 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5817 */
5818 Intent getSecondaryHomeIntent(String preferredPackage) {
5819 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005820 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5821 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5822 if (preferredPackage == null || useSystemProvidedLauncher) {
5823 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005824 final String secondaryHomeComponent = mContext.getResources().getString(
5825 com.android.internal.R.string.config_secondaryHomeComponent);
5826 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5827 } else {
5828 intent.setPackage(preferredPackage);
5829 }
5830 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5831 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5832 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5833 }
5834 return intent;
5835 }
5836
Wale Ogunwale214f3482018-10-04 11:00:47 -07005837 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5838 if (info == null) return null;
5839 ApplicationInfo newInfo = new ApplicationInfo(info);
5840 newInfo.initForUser(userId);
5841 return newInfo;
5842 }
5843
Wale Ogunwale9c103022018-10-18 07:44:54 -07005844 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005845 if (uid == SYSTEM_UID) {
5846 // The system gets to run in any process. If there are multiple processes with the same
5847 // uid, just pick the first (this should never happen).
5848 final SparseArray<WindowProcessController> procs =
5849 mProcessNames.getMap().get(processName);
5850 if (procs == null) return null;
5851 final int procCount = procs.size();
5852 for (int i = 0; i < procCount; i++) {
5853 final int procUid = procs.keyAt(i);
5854 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5855 // Don't use an app process or different user process for system component.
5856 continue;
5857 }
5858 return procs.valueAt(i);
5859 }
5860 }
5861
5862 return mProcessNames.get(processName, uid);
5863 }
5864
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005865 WindowProcessController getProcessController(IApplicationThread thread) {
5866 if (thread == null) {
5867 return null;
5868 }
5869
5870 final IBinder threadBinder = thread.asBinder();
5871 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5872 for (int i = pmap.size()-1; i >= 0; i--) {
5873 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5874 for (int j = procs.size() - 1; j >= 0; j--) {
5875 final WindowProcessController proc = procs.valueAt(j);
5876 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5877 return proc;
5878 }
5879 }
5880 }
5881
5882 return null;
5883 }
5884
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005885 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005886 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005887 if (proc == null) return null;
5888 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5889 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005890 }
5891 return null;
5892 }
5893
Riddle Hsua0536432019-02-16 00:38:59 +08005894 int getUidState(int uid) {
5895 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005896 }
5897
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005898 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005899 // A uid is considered to be foreground if it has a visible non-toast window.
5900 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005901 }
5902
Ricky Wai96f5c352019-04-10 18:40:17 +01005903 boolean isDeviceOwner(int uid) {
5904 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005905 }
5906
Ricky Wai96f5c352019-04-10 18:40:17 +01005907 void setDeviceOwnerUid(int uid) {
5908 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005909 }
5910
Wale Ogunwale9de19442018-10-18 19:05:03 -07005911 /**
5912 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5913 * the whitelist
5914 */
5915 String getPendingTempWhitelistTagForUidLocked(int uid) {
5916 return mPendingTempWhitelist.get(uid);
5917 }
5918
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005919 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5920 if (true || Build.IS_USER) {
5921 return;
5922 }
5923
5924 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5925 StrictMode.allowThreadDiskWrites();
5926 try {
5927 File tracesDir = new File("/data/anr");
5928 File tracesFile = null;
5929 try {
5930 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5931
5932 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005933 String timeString =
5934 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5935 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005936 sb.append(": ");
5937 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5938 sb.append(" since ");
5939 sb.append(msg);
5940 FileOutputStream fos = new FileOutputStream(tracesFile);
5941 fos.write(sb.toString().getBytes());
5942 if (app == null) {
5943 fos.write("\n*** No application process!".getBytes());
5944 }
5945 fos.close();
5946 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5947 } catch (IOException e) {
5948 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5949 return;
5950 }
5951
5952 if (app != null && app.getPid() > 0) {
5953 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5954 firstPids.add(app.getPid());
5955 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5956 }
5957
5958 File lastTracesFile = null;
5959 File curTracesFile = null;
5960 for (int i=9; i>=0; i--) {
5961 String name = String.format(Locale.US, "slow%02d.txt", i);
5962 curTracesFile = new File(tracesDir, name);
5963 if (curTracesFile.exists()) {
5964 if (lastTracesFile != null) {
5965 curTracesFile.renameTo(lastTracesFile);
5966 } else {
5967 curTracesFile.delete();
5968 }
5969 }
5970 lastTracesFile = curTracesFile;
5971 }
5972 tracesFile.renameTo(curTracesFile);
5973 } finally {
5974 StrictMode.setThreadPolicy(oldPolicy);
5975 }
5976 }
5977
Michal Karpinskida34cd42019-04-02 19:46:52 +01005978 boolean isAssociatedCompanionApp(int userId, int uid) {
5979 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5980 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005981 return false;
5982 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005983 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005984 }
5985
Issei Suzuki734bc942019-06-05 13:59:52 +02005986 void notifySingleTaskDisplayEmpty(int displayId) {
5987 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5988 }
5989
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005990 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005991 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005992
5993
Wale Ogunwale98875612018-10-12 07:53:02 -07005994 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5995 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005996
Riddle Hsud93a6c42018-11-29 21:50:06 +08005997 H(Looper looper) {
5998 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005999 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006000
6001 @Override
6002 public void handleMessage(Message msg) {
6003 switch (msg.what) {
6004 case REPORT_TIME_TRACKER_MSG: {
6005 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6006 tracker.deliverResult(mContext);
6007 } break;
6008 }
6009 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006010 }
6011
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006012 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006013 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006014
6015 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006016 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006017 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006018
6019 @Override
6020 public void handleMessage(Message msg) {
6021 switch (msg.what) {
6022 case DISMISS_DIALOG_UI_MSG: {
6023 final Dialog d = (Dialog) msg.obj;
6024 d.dismiss();
6025 break;
6026 }
6027 }
6028 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006029 }
6030
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 final class LocalService extends ActivityTaskManagerInternal {
6032 @Override
6033 public SleepToken acquireSleepToken(String tag, int displayId) {
6034 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006035 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006036 }
6037
6038 @Override
6039 public ComponentName getHomeActivityForUser(int userId) {
6040 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006041 final ActivityRecord homeActivity =
6042 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006043 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006044 }
6045 }
6046
6047 @Override
6048 public void onLocalVoiceInteractionStarted(IBinder activity,
6049 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6050 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006051 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006052 }
6053 }
6054
6055 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006056 public void notifyAppTransitionStarting(SparseIntArray reasons,
Yan Wangd47f90b2019-10-03 19:17:15 -07006057 long timestampNs) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006058 synchronized (mGlobalLock) {
6059 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
Yan Wangd47f90b2019-10-03 19:17:15 -07006060 reasons, timestampNs);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062 }
6063
6064 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006065 public void notifySingleTaskDisplayDrawn(int displayId) {
6066 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6067 }
6068
6069 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006070 public void notifyAppTransitionFinished() {
6071 synchronized (mGlobalLock) {
6072 mStackSupervisor.notifyAppTransitionDone();
6073 }
6074 }
6075
6076 @Override
6077 public void notifyAppTransitionCancelled() {
6078 synchronized (mGlobalLock) {
6079 mStackSupervisor.notifyAppTransitionDone();
6080 }
6081 }
6082
6083 @Override
6084 public List<IBinder> getTopVisibleActivities() {
6085 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006086 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006087 }
6088 }
6089
6090 @Override
6091 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6092 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006093 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006094 }
6095 }
6096
6097 @Override
6098 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6099 Bundle bOptions) {
6100 Preconditions.checkNotNull(intents, "intents");
6101 final String[] resolvedTypes = new String[intents.length];
6102
6103 // UID of the package on user userId.
6104 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6105 // packageUid may not be initialized.
6106 int packageUid = 0;
6107 final long ident = Binder.clearCallingIdentity();
6108
6109 try {
6110 for (int i = 0; i < intents.length; i++) {
6111 resolvedTypes[i] =
6112 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6113 }
6114
6115 packageUid = AppGlobals.getPackageManager().getPackageUid(
6116 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6117 } catch (RemoteException e) {
6118 // Shouldn't happen.
6119 } finally {
6120 Binder.restoreCallingIdentity(ident);
6121 }
6122
Riddle Hsu591bf612019-02-14 17:55:31 +08006123 return getActivityStartController().startActivitiesInPackage(
6124 packageUid, packageName,
6125 intents, resolvedTypes, null /* resultTo */,
6126 SafeActivityOptions.fromBundle(bOptions), userId,
6127 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6128 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 }
6130
6131 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006132 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6133 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6134 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6135 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006136 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006137 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006138 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6139 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6140 userId, validateIncomingUser, originatingPendingIntent,
6141 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006142 }
6143 }
6144
6145 @Override
6146 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6147 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6148 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6149 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006150 PendingIntentRecord originatingPendingIntent,
6151 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006152 synchronized (mGlobalLock) {
6153 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6154 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6155 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006156 validateIncomingUser, originatingPendingIntent,
6157 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006158 }
6159 }
6160
6161 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6163 Intent intent, Bundle options, int userId) {
6164 return ActivityTaskManagerService.this.startActivityAsUser(
6165 caller, callerPacakge, intent,
6166 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6167 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6168 false /*validateIncomingUser*/);
6169 }
6170
6171 @Override
lumark588a3e82018-07-20 18:53:54 +08006172 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006173 synchronized (mGlobalLock) {
6174
6175 // We might change the visibilities here, so prepare an empty app transition which
6176 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006177 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006178 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006179 if (activityDisplay == null) {
6180 return;
6181 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006182 final DisplayContent dc = activityDisplay.mDisplayContent;
6183 final boolean wasTransitionSet =
6184 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006185 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006186 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006187 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006188 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189
6190 // If there was a transition set already we don't want to interfere with it as we
6191 // might be starting it too early.
6192 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006193 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 }
6195 }
6196 if (callback != null) {
6197 callback.run();
6198 }
6199 }
6200
6201 @Override
6202 public void notifyKeyguardTrustedChanged() {
6203 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006204 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006205 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006206 }
6207 }
6208 }
6209
6210 /**
6211 * Called after virtual display Id is updated by
6212 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6213 * {@param vrVr2dDisplayId}.
6214 */
6215 @Override
6216 public void setVr2dDisplayId(int vr2dDisplayId) {
6217 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6218 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006219 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006220 }
6221 }
6222
6223 @Override
6224 public void setFocusedActivity(IBinder token) {
6225 synchronized (mGlobalLock) {
6226 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6227 if (r == null) {
6228 throw new IllegalArgumentException(
6229 "setFocusedActivity: No activity record matching token=" + token);
6230 }
Louis Chang19443452018-10-09 12:10:21 +08006231 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006232 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006233 }
6234 }
6235 }
6236
6237 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006239 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 }
6241
6242 @Override
6243 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006244 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006245 }
6246
6247 @Override
6248 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006249 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 }
6251
6252 @Override
6253 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6254 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6255 }
6256
6257 @Override
6258 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006259 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006261
6262 @Override
6263 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6264 synchronized (mGlobalLock) {
6265 mActiveVoiceInteractionServiceComponent = component;
6266 }
6267 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006268
6269 @Override
6270 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6271 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6272 return;
6273 }
6274 synchronized (mGlobalLock) {
6275 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6276 if (types == null) {
6277 if (uid < 0) {
6278 return;
6279 }
6280 types = new ArrayMap<>();
6281 mAllowAppSwitchUids.put(userId, types);
6282 }
6283 if (uid < 0) {
6284 types.remove(type);
6285 } else {
6286 types.put(type, uid);
6287 }
6288 }
6289 }
6290
6291 @Override
6292 public void onUserStopped(int userId) {
6293 synchronized (mGlobalLock) {
6294 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6295 mAllowAppSwitchUids.remove(userId);
6296 }
6297 }
6298
6299 @Override
6300 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6301 synchronized (mGlobalLock) {
6302 return ActivityTaskManagerService.this.isGetTasksAllowed(
6303 caller, callingPid, callingUid);
6304 }
6305 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006306
Riddle Hsua0536432019-02-16 00:38:59 +08006307 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006308 @Override
6309 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006310 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006311 mProcessNames.put(proc.mName, proc.mUid, proc);
6312 }
6313 }
6314
Riddle Hsua0536432019-02-16 00:38:59 +08006315 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006316 @Override
6317 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006318 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006319 mProcessNames.remove(name, uid);
6320 }
6321 }
6322
Riddle Hsua0536432019-02-16 00:38:59 +08006323 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006324 @Override
6325 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006326 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006327 if (proc == mHomeProcess) {
6328 mHomeProcess = null;
6329 }
6330 if (proc == mPreviousProcess) {
6331 mPreviousProcess = null;
6332 }
6333 }
6334 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006335
Riddle Hsua0536432019-02-16 00:38:59 +08006336 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006337 @Override
6338 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006339 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006340 return mTopProcessState;
6341 }
6342 }
6343
Riddle Hsua0536432019-02-16 00:38:59 +08006344 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006345 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006346 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006347 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006348 return proc == mHeavyWeightProcess;
6349 }
6350 }
6351
Riddle Hsua0536432019-02-16 00:38:59 +08006352 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006353 @Override
6354 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006355 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006356 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6357 }
6358 }
6359
6360 @Override
6361 public void finishHeavyWeightApp() {
6362 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006363 if (mHeavyWeightProcess != null) {
6364 mHeavyWeightProcess.finishActivities();
6365 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006366 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6367 mHeavyWeightProcess);
6368 }
6369 }
6370
Riddle Hsua0536432019-02-16 00:38:59 +08006371 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006372 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006373 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006374 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006375 return isSleepingLocked();
6376 }
6377 }
6378
6379 @Override
6380 public boolean isShuttingDown() {
6381 synchronized (mGlobalLock) {
6382 return mShuttingDown;
6383 }
6384 }
6385
6386 @Override
6387 public boolean shuttingDown(boolean booted, int timeout) {
6388 synchronized (mGlobalLock) {
6389 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006390 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006391 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006392 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006393 return mStackSupervisor.shutdownLocked(timeout);
6394 }
6395 }
6396
6397 @Override
6398 public void enableScreenAfterBoot(boolean booted) {
6399 synchronized (mGlobalLock) {
6400 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6401 SystemClock.uptimeMillis());
6402 mWindowManager.enableScreenAfterBoot();
6403 updateEventDispatchingLocked(booted);
6404 }
6405 }
6406
6407 @Override
6408 public boolean showStrictModeViolationDialog() {
6409 synchronized (mGlobalLock) {
6410 return mShowDialogs && !mSleeping && !mShuttingDown;
6411 }
6412 }
6413
6414 @Override
6415 public void showSystemReadyErrorDialogsIfNeeded() {
6416 synchronized (mGlobalLock) {
6417 try {
6418 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6419 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6420 + " data partition or your device will be unstable.");
6421 mUiHandler.post(() -> {
6422 if (mShowDialogs) {
6423 AlertDialog d = new BaseErrorDialog(mUiContext);
6424 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6425 d.setCancelable(false);
6426 d.setTitle(mUiContext.getText(R.string.android_system_label));
6427 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6428 d.setButton(DialogInterface.BUTTON_POSITIVE,
6429 mUiContext.getText(R.string.ok),
6430 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6431 d.show();
6432 }
6433 });
6434 }
6435 } catch (RemoteException e) {
6436 }
6437
6438 if (!Build.isBuildConsistent()) {
6439 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6440 mUiHandler.post(() -> {
6441 if (mShowDialogs) {
6442 AlertDialog d = new BaseErrorDialog(mUiContext);
6443 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6444 d.setCancelable(false);
6445 d.setTitle(mUiContext.getText(R.string.android_system_label));
6446 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6447 d.setButton(DialogInterface.BUTTON_POSITIVE,
6448 mUiContext.getText(R.string.ok),
6449 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6450 d.show();
6451 }
6452 });
6453 }
6454 }
6455 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006456
6457 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006458 public void onProcessMapped(int pid, WindowProcessController proc) {
6459 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006460 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006461 }
6462 }
6463
6464 @Override
6465 public void onProcessUnMapped(int pid) {
6466 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006467 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006468 }
6469 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006470
6471 @Override
6472 public void onPackageDataCleared(String name) {
6473 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006474 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006475 mAppWarnings.onPackageDataCleared(name);
6476 }
6477 }
6478
6479 @Override
6480 public void onPackageUninstalled(String name) {
6481 synchronized (mGlobalLock) {
6482 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006483 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006484 }
6485 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006486
6487 @Override
6488 public void onPackageAdded(String name, boolean replacing) {
6489 synchronized (mGlobalLock) {
6490 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6491 }
6492 }
6493
6494 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006495 public void onPackageReplaced(ApplicationInfo aInfo) {
6496 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006497 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006498 }
6499 }
6500
6501 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006502 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6503 synchronized (mGlobalLock) {
6504 return compatibilityInfoForPackageLocked(ai);
6505 }
6506 }
6507
Yunfan Chen75157d72018-07-27 14:47:21 +09006508 /**
6509 * Set the corresponding display information for the process global configuration. To be
6510 * called when we need to show IME on a different display.
6511 *
6512 * @param pid The process id associated with the IME window.
6513 * @param displayId The ID of the display showing the IME.
6514 */
6515 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006516 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006517 // Don't update process-level configuration for Multi-Client IME process since other
6518 // IMEs on other displays will also receive this configuration change due to IME
6519 // services use the same application config/context.
6520 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006521
Yunfan Chen75157d72018-07-27 14:47:21 +09006522 if (pid == MY_PID || pid < 0) {
6523 if (DEBUG_CONFIGURATION) {
6524 Slog.w(TAG,
6525 "Trying to update display configuration for system/invalid process.");
6526 }
6527 return;
6528 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006529 synchronized (mGlobalLock) {
6530 final ActivityDisplay activityDisplay =
6531 mRootActivityContainer.getActivityDisplay(displayId);
6532 if (activityDisplay == null) {
6533 // Call might come when display is not yet added or has been removed.
6534 if (DEBUG_CONFIGURATION) {
6535 Slog.w(TAG, "Trying to update display configuration for non-existing "
6536 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006537 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006538 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006539 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006540 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006541 if (process == null) {
6542 if (DEBUG_CONFIGURATION) {
6543 Slog.w(TAG, "Trying to update display configuration for invalid "
6544 + "process, pid=" + pid);
6545 }
6546 return;
6547 }
lumarkddc77fb2019-06-27 22:22:23 +08006548 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006549 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6550 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006551 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006552
6553 @Override
6554 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006555 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006556 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006557 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6558 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006559 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006560 }
6561 }
6562 }
6563
6564 @Override
6565 public void clearPendingResultForActivity(IBinder activityToken,
6566 WeakReference<PendingIntentRecord> pir) {
6567 synchronized (mGlobalLock) {
6568 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6569 if (r != null && r.pendingResults != null) {
6570 r.pendingResults.remove(pir);
6571 }
6572 }
6573 }
6574
6575 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006576 public ActivityTokens getTopActivityForTask(int taskId) {
6577 synchronized (mGlobalLock) {
6578 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6579 if (taskRecord == null) {
6580 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6581 + " Requested task not found");
6582 return null;
6583 }
6584 final ActivityRecord activity = taskRecord.getTopActivity();
6585 if (activity == null) {
6586 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6587 + " Requested activity not found");
6588 return null;
6589 }
6590 if (!activity.attachedToProcess()) {
6591 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6592 + activity);
6593 return null;
6594 }
6595 return new ActivityTokens(activity.appToken, activity.assistToken,
6596 activity.app.getThread());
6597 }
6598 }
6599
6600 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006601 public IIntentSender getIntentSender(int type, String packageName,
6602 int callingUid, int userId, IBinder token, String resultWho,
6603 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6604 Bundle bOptions) {
6605 synchronized (mGlobalLock) {
6606 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6607 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6608 }
6609 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006610
6611 @Override
6612 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6613 synchronized (mGlobalLock) {
6614 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6615 if (r == null) {
6616 return null;
6617 }
6618 if (r.mServiceConnectionsHolder == null) {
6619 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6620 ActivityTaskManagerService.this, r);
6621 }
6622
6623 return r.mServiceConnectionsHolder;
6624 }
6625 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006626
6627 @Override
6628 public Intent getHomeIntent() {
6629 synchronized (mGlobalLock) {
6630 return ActivityTaskManagerService.this.getHomeIntent();
6631 }
6632 }
6633
6634 @Override
6635 public boolean startHomeActivity(int userId, String reason) {
6636 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006637 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006638 }
6639 }
6640
6641 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006642 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006643 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006644 synchronized (mGlobalLock) {
6645 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006646 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006647 }
Chilun8b1f1be2019-03-13 17:14:36 +08006648 }
6649
6650 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006651 public boolean startHomeOnAllDisplays(int userId, String reason) {
6652 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006653 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006654 }
6655 }
6656
Riddle Hsua0536432019-02-16 00:38:59 +08006657 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006658 @Override
6659 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006660 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006661 if (mFactoryTest == FACTORY_TEST_OFF) {
6662 return false;
6663 }
6664 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6665 && wpc.mName.equals(mTopComponent.getPackageName())) {
6666 return true;
6667 }
6668 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6669 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6670 }
6671 }
6672
6673 @Override
6674 public void updateTopComponentForFactoryTest() {
6675 synchronized (mGlobalLock) {
6676 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6677 return;
6678 }
6679 final ResolveInfo ri = mContext.getPackageManager()
6680 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6681 final CharSequence errorMsg;
6682 if (ri != null) {
6683 final ActivityInfo ai = ri.activityInfo;
6684 final ApplicationInfo app = ai.applicationInfo;
6685 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6686 mTopAction = Intent.ACTION_FACTORY_TEST;
6687 mTopData = null;
6688 mTopComponent = new ComponentName(app.packageName, ai.name);
6689 errorMsg = null;
6690 } else {
6691 errorMsg = mContext.getResources().getText(
6692 com.android.internal.R.string.factorytest_not_system);
6693 }
6694 } else {
6695 errorMsg = mContext.getResources().getText(
6696 com.android.internal.R.string.factorytest_no_action);
6697 }
6698 if (errorMsg == null) {
6699 return;
6700 }
6701
6702 mTopAction = null;
6703 mTopData = null;
6704 mTopComponent = null;
6705 mUiHandler.post(() -> {
6706 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6707 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006708 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006709 });
6710 }
6711 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006712
Riddle Hsua0536432019-02-16 00:38:59 +08006713 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006714 @Override
6715 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6716 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006717 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006719 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006720
6721 wpc.clearRecentTasks();
6722 wpc.clearActivities();
6723
6724 if (wpc.isInstrumenting()) {
6725 finishInstrumentationCallback.run();
6726 }
6727
Jorim Jaggid0752812018-10-16 16:07:20 +02006728 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006729 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006730 try {
6731 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6732 // If there was nothing to resume, and we are not already restarting
6733 // this process, but there is a visible activity that is hosted by the
6734 // process...then make sure all visible activities are running, taking
6735 // care of restarting this process.
6736 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6737 !PRESERVE_WINDOWS);
6738 }
6739 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006740 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006741 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006742 }
6743 }
6744 }
6745
6746 @Override
6747 public void closeSystemDialogs(String reason) {
6748 enforceNotIsolatedCaller("closeSystemDialogs");
6749
6750 final int pid = Binder.getCallingPid();
6751 final int uid = Binder.getCallingUid();
6752 final long origId = Binder.clearCallingIdentity();
6753 try {
6754 synchronized (mGlobalLock) {
6755 // Only allow this from foreground processes, so that background
6756 // applications can't abuse it to prevent system UI from being shown.
6757 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006758 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 if (!proc.isPerceptible()) {
6760 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6761 + " from background process " + proc);
6762 return;
6763 }
6764 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 mWindowManager.closeSystemDialogs(reason);
6766
Wale Ogunwaled32da472018-11-16 07:19:28 -08006767 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006769 // Call into AM outside the synchronized block.
6770 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 } finally {
6772 Binder.restoreCallingIdentity(origId);
6773 }
6774 }
6775
6776 @Override
6777 public void cleanupDisabledPackageComponents(
6778 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6779 synchronized (mGlobalLock) {
6780 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006781 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006783 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 mStackSupervisor.scheduleIdleLocked();
6785 }
6786
6787 // Clean-up disabled tasks
6788 getRecentTasks().cleanupDisabledPackageTasksLocked(
6789 packageName, disabledClasses, userId);
6790 }
6791 }
6792
6793 @Override
6794 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6795 int userId) {
6796 synchronized (mGlobalLock) {
6797
6798 boolean didSomething =
6799 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006800 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006801 null, doit, evenPersistent, userId);
6802 return didSomething;
6803 }
6804 }
6805
6806 @Override
6807 public void resumeTopActivities(boolean scheduleIdle) {
6808 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006809 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006810 if (scheduleIdle) {
6811 mStackSupervisor.scheduleIdleLocked();
6812 }
6813 }
6814 }
6815
Riddle Hsua0536432019-02-16 00:38:59 +08006816 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 @Override
6818 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006819 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6821 }
6822 }
6823
Riddle Hsua0536432019-02-16 00:38:59 +08006824 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 @Override
6826 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006827 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006828 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6829 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6830 }
6831 try {
6832 return mRootActivityContainer.attachApplication(wpc);
6833 } finally {
6834 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6835 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 }
6837 }
6838
6839 @Override
6840 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6841 try {
6842 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6843 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6844 }
6845 } catch (RemoteException ex) {
6846 throw new SecurityException("Fail to check is caller a privileged app", ex);
6847 }
6848
6849 synchronized (mGlobalLock) {
6850 final long ident = Binder.clearCallingIdentity();
6851 try {
6852 if (mAmInternal.shouldConfirmCredentials(userId)) {
6853 if (mKeyguardController.isKeyguardLocked()) {
6854 // Showing launcher to avoid user entering credential twice.
6855 startHomeActivity(currentUserId, "notifyLockedProfile");
6856 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006857 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 }
6859 } finally {
6860 Binder.restoreCallingIdentity(ident);
6861 }
6862 }
6863 }
6864
6865 @Override
6866 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6867 mAmInternal.enforceCallingPermission(
6868 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6869
6870 synchronized (mGlobalLock) {
6871 final long ident = Binder.clearCallingIdentity();
6872 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006873 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6874 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006875 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6877 UserHandle.CURRENT);
6878 } finally {
6879 Binder.restoreCallingIdentity(ident);
6880 }
6881 }
6882 }
6883
6884 @Override
6885 public void writeActivitiesToProto(ProtoOutputStream proto) {
6886 synchronized (mGlobalLock) {
6887 // The output proto of "activity --proto activities"
6888 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006889 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006890 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6891 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
6893 }
6894
6895 @Override
6896 public void saveANRState(String reason) {
6897 synchronized (mGlobalLock) {
6898 final StringWriter sw = new StringWriter();
6899 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6900 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6901 if (reason != null) {
6902 pw.println(" Reason: " + reason);
6903 }
6904 pw.println();
6905 getActivityStartController().dump(pw, " ", null);
6906 pw.println();
6907 pw.println("-------------------------------------------------------------------------------");
6908 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6909 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6910 "" /* header */);
6911 pw.println();
6912 pw.close();
6913
6914 mLastANRState = sw.toString();
6915 }
6916 }
6917
6918 @Override
6919 public void clearSavedANRState() {
6920 synchronized (mGlobalLock) {
6921 mLastANRState = null;
6922 }
6923 }
6924
6925 @Override
6926 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6927 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6928 synchronized (mGlobalLock) {
6929 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6930 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6931 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6932 dumpLastANRLocked(pw);
6933 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6934 dumpLastANRTracesLocked(pw);
6935 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6936 dumpActivityStarterLocked(pw, dumpPackage);
6937 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6938 dumpActivityContainersLocked(pw);
6939 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6940 if (getRecentTasks() != null) {
6941 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6942 }
6943 }
6944 }
6945 }
6946
6947 @Override
6948 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6949 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6950 int wakefulness) {
6951 synchronized (mGlobalLock) {
6952 if (mHomeProcess != null && (dumpPackage == null
6953 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6954 if (needSep) {
6955 pw.println();
6956 needSep = false;
6957 }
6958 pw.println(" mHomeProcess: " + mHomeProcess);
6959 }
6960 if (mPreviousProcess != null && (dumpPackage == null
6961 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6962 if (needSep) {
6963 pw.println();
6964 needSep = false;
6965 }
6966 pw.println(" mPreviousProcess: " + mPreviousProcess);
6967 }
6968 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6969 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6970 StringBuilder sb = new StringBuilder(128);
6971 sb.append(" mPreviousProcessVisibleTime: ");
6972 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6973 pw.println(sb);
6974 }
6975 if (mHeavyWeightProcess != null && (dumpPackage == null
6976 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6977 if (needSep) {
6978 pw.println();
6979 needSep = false;
6980 }
6981 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6982 }
6983 if (dumpPackage == null) {
6984 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006985 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 }
6987 if (dumpAll) {
6988 if (dumpPackage == null) {
6989 pw.println(" mConfigWillChange: "
6990 + getTopDisplayFocusedStack().mConfigWillChange);
6991 }
6992 if (mCompatModePackages.getPackages().size() > 0) {
6993 boolean printed = false;
6994 for (Map.Entry<String, Integer> entry
6995 : mCompatModePackages.getPackages().entrySet()) {
6996 String pkg = entry.getKey();
6997 int mode = entry.getValue();
6998 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6999 continue;
7000 }
7001 if (!printed) {
7002 pw.println(" mScreenCompatPackages:");
7003 printed = true;
7004 }
7005 pw.println(" " + pkg + ": " + mode);
7006 }
7007 }
7008 }
7009
7010 if (dumpPackage == null) {
7011 pw.println(" mWakefulness="
7012 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007013 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 if (mRunningVoice != null) {
7015 pw.println(" mRunningVoice=" + mRunningVoice);
7016 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7017 }
7018 pw.println(" mSleeping=" + mSleeping);
7019 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7020 pw.println(" mVrController=" + mVrController);
7021 }
7022 if (mCurAppTimeTracker != null) {
7023 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7024 }
7025 if (mAllowAppSwitchUids.size() > 0) {
7026 boolean printed = false;
7027 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7028 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7029 for (int j = 0; j < types.size(); j++) {
7030 if (dumpPackage == null ||
7031 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7032 if (needSep) {
7033 pw.println();
7034 needSep = false;
7035 }
7036 if (!printed) {
7037 pw.println(" mAllowAppSwitchUids:");
7038 printed = true;
7039 }
7040 pw.print(" User ");
7041 pw.print(mAllowAppSwitchUids.keyAt(i));
7042 pw.print(": Type ");
7043 pw.print(types.keyAt(j));
7044 pw.print(" = ");
7045 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7046 pw.println();
7047 }
7048 }
7049 }
7050 }
7051 if (dumpPackage == null) {
7052 if (mController != null) {
7053 pw.println(" mController=" + mController
7054 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7055 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007056 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7057 pw.println(" mLaunchingActivityWakeLock="
7058 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007059 }
7060
7061 return needSep;
7062 }
7063 }
7064
7065 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007066 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7067 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007068 synchronized (mGlobalLock) {
7069 if (dumpPackage == null) {
7070 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7071 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007072 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7073 if (mRunningVoice != null) {
7074 final long vrToken = proto.start(
7075 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7076 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7077 mRunningVoice.toString());
7078 mVoiceWakeLock.writeToProto(
7079 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7080 proto.end(vrToken);
7081 }
7082 mVrController.writeToProto(proto,
7083 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 if (mController != null) {
7085 final long token = proto.start(CONTROLLER);
7086 proto.write(CONTROLLER, mController.toString());
7087 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7088 proto.end(token);
7089 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007090 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7091 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7092 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 }
7094
7095 if (mHomeProcess != null && (dumpPackage == null
7096 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007097 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007098 }
7099
7100 if (mPreviousProcess != null && (dumpPackage == null
7101 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007102 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007103 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7104 }
7105
7106 if (mHeavyWeightProcess != null && (dumpPackage == null
7107 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007108 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 }
7110
7111 for (Map.Entry<String, Integer> entry
7112 : mCompatModePackages.getPackages().entrySet()) {
7113 String pkg = entry.getKey();
7114 int mode = entry.getValue();
7115 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7116 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7117 proto.write(PACKAGE, pkg);
7118 proto.write(MODE, mode);
7119 proto.end(compatToken);
7120 }
7121 }
7122
7123 if (mCurAppTimeTracker != null) {
7124 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7125 }
7126
7127 }
7128 }
7129
7130 @Override
7131 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7132 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7133 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007134 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7135 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007136 }
7137
7138 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007139 public void dumpForOom(PrintWriter pw) {
7140 synchronized (mGlobalLock) {
7141 pw.println(" mHomeProcess: " + mHomeProcess);
7142 pw.println(" mPreviousProcess: " + mPreviousProcess);
7143 if (mHeavyWeightProcess != null) {
7144 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7145 }
7146 }
7147 }
7148
7149 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007150 public boolean canGcNow() {
7151 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007152 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007153 }
7154 }
7155
Riddle Hsua0536432019-02-16 00:38:59 +08007156 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 @Override
7158 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007159 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007160 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 return top != null ? top.app : null;
7162 }
7163 }
7164
Riddle Hsua0536432019-02-16 00:38:59 +08007165 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007166 @Override
7167 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007168 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007169 if (mRootActivityContainer != null) {
7170 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007171 }
7172 }
7173 }
7174
7175 @Override
7176 public void scheduleDestroyAllActivities(String reason) {
7177 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007178 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 }
7180 }
7181
7182 @Override
7183 public void removeUser(int userId) {
7184 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007185 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007186 }
7187 }
7188
7189 @Override
7190 public boolean switchUser(int userId, UserState userState) {
7191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007192 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007193 }
7194 }
7195
7196 @Override
7197 public void onHandleAppCrash(WindowProcessController wpc) {
7198 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007199 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007200 }
7201 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007202
7203 @Override
7204 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7205 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007206 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007207 }
7208 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007209
Riddle Hsua0536432019-02-16 00:38:59 +08007210 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007211 @Override
7212 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007213 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007214 }
7215
Riddle Hsua0536432019-02-16 00:38:59 +08007216 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007217 @Override
7218 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007219 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007220 }
7221
Riddle Hsua0536432019-02-16 00:38:59 +08007222 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007223 @Override
7224 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007225 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007226 }
7227
Riddle Hsua0536432019-02-16 00:38:59 +08007228 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007229 @Override
7230 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007231 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007232 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007233
7234 @Override
7235 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007236 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007237 mPendingTempWhitelist.put(uid, tag);
7238 }
7239 }
7240
7241 @Override
7242 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007243 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007244 mPendingTempWhitelist.remove(uid);
7245 }
7246 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007247
7248 @Override
7249 public boolean handleAppCrashInActivityController(String processName, int pid,
7250 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7251 Runnable killCrashingAppCallback) {
7252 synchronized (mGlobalLock) {
7253 if (mController == null) {
7254 return false;
7255 }
7256
7257 try {
7258 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7259 stackTrace)) {
7260 killCrashingAppCallback.run();
7261 return true;
7262 }
7263 } catch (RemoteException e) {
7264 mController = null;
7265 Watchdog.getInstance().setActivityController(null);
7266 }
7267 return false;
7268 }
7269 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007270
7271 @Override
7272 public void removeRecentTasksByPackageName(String packageName, int userId) {
7273 synchronized (mGlobalLock) {
7274 mRecentTasks.removeTasksByPackageName(packageName, userId);
7275 }
7276 }
7277
7278 @Override
7279 public void cleanupRecentTasksForUser(int userId) {
7280 synchronized (mGlobalLock) {
7281 mRecentTasks.cleanupLocked(userId);
7282 }
7283 }
7284
7285 @Override
7286 public void loadRecentTasksForUser(int userId) {
7287 synchronized (mGlobalLock) {
7288 mRecentTasks.loadUserRecentsLocked(userId);
7289 }
7290 }
7291
7292 @Override
7293 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7294 synchronized (mGlobalLock) {
7295 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7296 }
7297 }
7298
7299 @Override
7300 public void flushRecentTasks() {
7301 mRecentTasks.flush();
7302 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007303
7304 @Override
7305 public WindowProcessController getHomeProcess() {
7306 synchronized (mGlobalLock) {
7307 return mHomeProcess;
7308 }
7309 }
7310
7311 @Override
7312 public WindowProcessController getPreviousProcess() {
7313 synchronized (mGlobalLock) {
7314 return mPreviousProcess;
7315 }
7316 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007317
7318 @Override
7319 public void clearLockedTasks(String reason) {
7320 synchronized (mGlobalLock) {
7321 getLockTaskController().clearLockedTasks(reason);
7322 }
7323 }
7324
7325 @Override
7326 public void updateUserConfiguration() {
7327 synchronized (mGlobalLock) {
7328 final Configuration configuration = new Configuration(getGlobalConfiguration());
7329 final int currentUserId = mAmInternal.getCurrentUserId();
7330 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7331 configuration, currentUserId, Settings.System.canWrite(mContext));
7332 updateConfigurationLocked(configuration, null /* starting */,
7333 false /* initLocale */, false /* persistent */, currentUserId,
7334 false /* deferResume */);
7335 }
7336 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007337
7338 @Override
7339 public boolean canShowErrorDialogs() {
7340 synchronized (mGlobalLock) {
7341 return mShowDialogs && !mSleeping && !mShuttingDown
7342 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7343 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7344 mAmInternal.getCurrentUserId())
7345 && !(UserManager.isDeviceInDemoMode(mContext)
7346 && mAmInternal.getCurrentUser().isDemo());
7347 }
7348 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007349
7350 @Override
7351 public void setProfileApp(String profileApp) {
7352 synchronized (mGlobalLock) {
7353 mProfileApp = profileApp;
7354 }
7355 }
7356
7357 @Override
7358 public void setProfileProc(WindowProcessController wpc) {
7359 synchronized (mGlobalLock) {
7360 mProfileProc = wpc;
7361 }
7362 }
7363
7364 @Override
7365 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7366 synchronized (mGlobalLock) {
7367 mProfilerInfo = profilerInfo;
7368 }
7369 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007370
7371 @Override
7372 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7373 synchronized (mGlobalLock) {
7374 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7375 }
7376 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007377
7378 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007379 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7380 boolean reducedResolution) {
7381 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7382 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007383 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007384
7385 @Override
7386 public boolean isUidForeground(int uid) {
7387 synchronized (mGlobalLock) {
7388 return ActivityTaskManagerService.this.isUidForeground(uid);
7389 }
7390 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007391
7392 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007393 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007394 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007395 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007396 }
7397 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007398
7399 @Override
7400 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007401 // Translate package names into UIDs
7402 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007403 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007404 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7405 if (uid >= 0) {
7406 result.add(uid);
7407 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007408 }
7409 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007410 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007411 }
7412 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007413 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007414}