blob: 3128536fbbfa06af3bdd5e13f9a06a90b6684535 [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;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800147import android.app.ITaskOrganizerController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700160import android.app.servertransaction.ClientTransaction;
161import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
215import android.service.voice.IVoiceInteractionSession;
216import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900217import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700218import android.telecom.TelecomManager;
219import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100220import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700222import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700224import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700232
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700234import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700238import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700244import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245import com.android.internal.policy.IKeyguardDismissCallback;
246import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700247import com.android.internal.util.ArrayUtils;
248import com.android.internal.util.FastPrintWriter;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800249import com.android.internal.util.FrameworkStatsLog;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800250import com.android.internal.util.function.pooled.PooledConsumer;
251import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700252import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700253import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.LocalServices;
255import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700256import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800257import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700258import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700259import com.android.server.am.ActivityManagerService;
260import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
261import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
262import com.android.server.am.AppTimeTracker;
263import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700264import com.android.server.am.PendingIntentController;
265import com.android.server.am.PendingIntentRecord;
266import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900267import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700268import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700269import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800271import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700281import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700282import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800283import java.lang.annotation.ElementType;
284import java.lang.annotation.Retention;
285import java.lang.annotation.RetentionPolicy;
286import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700287import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700290import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400292import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700293import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700295import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000297import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299
300/**
301 * System service for managing activities and their containers (task, stacks, displays,... ).
302 *
303 * {@hide}
304 */
305public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700306 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800307 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000308 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
310 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
311 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
312 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700313 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700314
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100319 // How long we permit background activity starts after an activity in the process
320 // started or finished.
321 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700322
Wale Ogunwale98875612018-10-12 07:53:02 -0700323 /** Used to indicate that an app transition should be animated. */
324 static final boolean ANIMATE = true;
325
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700326 /** Hardware-reported OpenGLES version. */
327 final int GL_ES_VERSION;
328
Wale Ogunwale31913b52018-10-13 08:29:31 -0700329 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
330 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
331 public static final String DUMP_LASTANR_CMD = "lastanr" ;
332 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
333 public static final String DUMP_STARTER_CMD = "starter" ;
334 public static final String DUMP_CONTAINERS_CMD = "containers" ;
335 public static final String DUMP_RECENTS_CMD = "recents" ;
336 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
337
Wale Ogunwale64258362018-10-16 15:13:37 -0700338 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
339 public static final int RELAUNCH_REASON_NONE = 0;
340 /** This activity is being relaunched due to windowing mode change. */
341 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
342 /** This activity is being relaunched due to a free-resize operation. */
343 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
344
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700345 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700346
Wale Ogunwalef6733932018-06-27 05:14:34 -0700347 /**
348 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
349 * change at runtime. Use mContext for non-UI purposes.
350 */
351 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700352 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700356 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800358 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800359 @VisibleForTesting
360 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 PowerManagerInternal mPowerManagerInternal;
362 private UsageStatsManagerInternal mUsageStatsInternal;
363
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700364 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700365 IntentFirewall mIntentFirewall;
366
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700367 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800368 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700370 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
372 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
373 *
374 * @see WindowManagerThreadPriorityBooster
375 */
376 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800378 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700379 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700380 private UserManagerService mUserManager;
381 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700382 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800383 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700384 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** All processes currently running that might have a window organized by name. */
386 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100387 /** All processes we currently have running mapped by pid and uid */
388 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /** This is the process holding what we currently consider to be the "home" activity. */
390 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700391 /** The currently running heavy-weight process, if any. */
392 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700393 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700394 /**
395 * This is the process holding the activity the user last visited that is in a different process
396 * from the one they are currently in.
397 */
398 WindowProcessController mPreviousProcess;
399 /** The time at which the previous process was last visible. */
400 long mPreviousProcessVisibleTime;
401
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700402 /** List of intents that were used to start the most recent tasks. */
403 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700404 /** State of external calls telling us if the device is awake or asleep. */
405 private boolean mKeyguardShown = false;
406
407 // Wrapper around VoiceInteractionServiceManager
408 private AssistUtils mAssistUtils;
409
410 // VoiceInteraction session ID that changes for each new request except when
411 // being called for multi-window assist in a single session.
412 private int mViSessionId = 1000;
413
414 // How long to wait in getAssistContextExtras for the activity and foreground services
415 // to respond with the result.
416 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
417
418 // How long top wait when going through the modern assist (which doesn't need to block
419 // on getting this result before starting to launch its UI).
420 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
421
422 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
423 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
424
Alison Cichowlas3e340502018-08-07 17:15:01 -0400425 // Permission tokens are used to temporarily granted a trusted app the ability to call
426 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
427 // showing any appropriate error messages to the user.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
429 10 * MINUTE_IN_MILLIS;
430
431 // How long before the service actually expires a token. This is slightly longer than
432 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
433 // expiration exception.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
435 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
436
437 // How long the service will remember expired tokens, for the purpose of providing error
438 // messaging when a client uses an expired token.
439 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
440 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
441
442 // Activity tokens of system activities that are delegating their call to
443 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
444 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
445
446 // Permission tokens that have expired, but we remember for error reporting.
447 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
448
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700449 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
450
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700451 // Keeps track of the active voice interaction service component, notified from
452 // VoiceInteractionManagerService
453 ComponentName mActiveVoiceInteractionServiceComponent;
454
Michal Karpinskida34cd42019-04-02 19:46:52 +0100455 // A map userId and all its companion app uids
456 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000457
Wale Ogunwalee2172292018-10-25 10:11:10 -0700458 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459 KeyguardController mKeyguardController;
460 private final ClientLifecycleManager mLifecycleManager;
461 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700462 /** The controller for all operations related to locktask. */
463 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700464 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700466 boolean mSuppressResizeConfigChanges;
467
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700468 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 new UpdateConfigurationResult();
470
471 static final class UpdateConfigurationResult {
472 // Configuration changes that were updated.
473 int changes;
474 // If the activity was relaunched to match the new configuration.
475 boolean activityRelaunched;
476
477 void reset() {
478 changes = 0;
479 activityRelaunched = false;
480 }
481 }
482
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484 private int mConfigurationSeq;
485 // To cache the list of supported system locales
486 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700487
488 /**
489 * Temp object used when global and/or display override configuration is updated. It is also
490 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
491 * anyone...
492 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 private Configuration mTempConfig = new Configuration();
494
Wale Ogunwalef6733932018-06-27 05:14:34 -0700495 /** Temporary to avoid allocations. */
496 final StringBuilder mStringBuilder = new StringBuilder(256);
497
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700498 // Amount of time after a call to stopAppSwitches() during which we will
499 // prevent further untrusted switches from happening.
500 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
501
502 /**
503 * The time at which we will allow normal application switches again,
504 * after a call to {@link #stopAppSwitches()}.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 /**
508 * This is set to true after the first switch after mAppSwitchesAllowedTime
509 * is set; any switches after that will clear the time.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
Ricky Wai906af482019-06-03 17:25:28 +0100513 /**
514 * Last stop app switches time, apps finished before this time cannot start background activity
515 * even if they are in grace period.
516 */
517 private long mLastStopAppSwitchesTime;
518
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519 IActivityController mController = null;
520 boolean mControllerIsAMonkey = false;
521
Wale Ogunwale214f3482018-10-04 11:00:47 -0700522 final int mFactoryTest;
523
524 /** Used to control how we initialize the service. */
525 ComponentName mTopComponent;
526 String mTopAction = Intent.ACTION_MAIN;
527 String mTopData;
528
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800529 /** Profiling app information. */
530 String mProfileApp = null;
531 WindowProcessController mProfileProc = null;
532 ProfilerInfo mProfilerInfo = null;
533
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700534 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700535 * Dump of the activity state at the time of the last ANR. Cleared after
536 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
537 */
538 String mLastANRState;
539
540 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541 * Used to retain an update lock when the foreground activity is in
542 * immersive mode.
543 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700544 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700545
546 /**
547 * Packages that are being allowed to perform unrestricted app switches. Mapping is
548 * User -> Type -> uid.
549 */
550 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
551
552 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700553 private int mThumbnailWidth;
554 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700576 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700577
578 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
579
580 // VR Vr2d Display Id.
581 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700582
Wale Ogunwalef6733932018-06-27 05:14:34 -0700583 /**
584 * Set while we are wanting to sleep, to prevent any
585 * activities from being started/resumed.
586 *
587 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
588 *
589 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
590 * while in the sleep state until there is a pending transition out of sleep, in which case
591 * mSleeping is set to false, and remains false while awake.
592 *
593 * Whether mSleeping can quickly toggled between true/false without the device actually
594 * display changing states is undefined.
595 */
596 private boolean mSleeping = false;
597
598 /**
599 * The process state used for processes that are running the top activities.
600 * This changes between TOP and TOP_SLEEPING to following mSleeping.
601 */
602 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
603
Riddle Hsua0022cd2019-09-09 21:12:41 +0800604 @Retention(RetentionPolicy.SOURCE)
605 @IntDef({
606 LAYOUT_REASON_CONFIG_CHANGED,
607 LAYOUT_REASON_VISIBILITY_CHANGED,
608 })
609 @interface LayoutReason {}
610 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
611 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
612
613 /** The reasons to perform surface placement. */
614 @LayoutReason
615 private int mLayoutReasons;
616
Wale Ogunwalef6733932018-06-27 05:14:34 -0700617 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
618 // automatically. Important for devices without direct input devices.
619 private boolean mShowDialogs = true;
620
621 /** Set if we are shutting down the system, similar to sleeping. */
622 boolean mShuttingDown = false;
623
624 /**
625 * We want to hold a wake lock while running a voice interaction session, since
626 * this may happen with the screen off and we need to keep the CPU running to
627 * be able to continue to interact with the user.
628 */
629 PowerManager.WakeLock mVoiceWakeLock;
630
631 /**
632 * Set while we are running a voice interaction. This overrides sleeping while it is active.
633 */
634 IVoiceInteractionSession mRunningVoice;
635
636 /**
637 * The last resumed activity. This is identical to the current resumed activity most
638 * of the time but could be different when we're pausing one activity before we resume
639 * another activity.
640 */
641 ActivityRecord mLastResumedActivity;
642
643 /**
644 * The activity that is currently being traced as the active resumed activity.
645 *
646 * @see #updateResumedAppTrace
647 */
648 private @Nullable ActivityRecord mTracedResumedActivity;
649
650 /** If non-null, we are tracking the time the user spends in the currently focused app. */
651 AppTimeTracker mCurAppTimeTracker;
652
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700653 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700654
Wale Ogunwale53783742018-09-16 10:21:51 -0700655 /**
656 * Packages that the user has asked to have run in screen size
657 * compatibility mode instead of filling the screen.
658 */
659 CompatModePackages mCompatModePackages;
660
Wale Ogunwalef6733932018-06-27 05:14:34 -0700661 private FontScaleSettingObserver mFontScaleSettingObserver;
662
Robert Carr8a2f9132019-11-11 15:03:15 -0800663 /**
664 * Stores the registration and state of TaskOrganizers in use.
665 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800666 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800667
Ricky Wai96f5c352019-04-10 18:40:17 +0100668 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000669
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 private final class FontScaleSettingObserver extends ContentObserver {
671 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
672 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
673
674 public FontScaleSettingObserver() {
675 super(mH);
676 final ContentResolver resolver = mContext.getContentResolver();
677 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
678 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
679 UserHandle.USER_ALL);
680 }
681
682 @Override
683 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
684 if (mFontScaleUri.equals(uri)) {
685 updateFontScaleIfNeeded(userId);
686 } else if (mHideErrorDialogsUri.equals(uri)) {
687 synchronized (mGlobalLock) {
688 updateShouldShowDialogsLocked(getGlobalConfiguration());
689 }
690 }
691 }
692 }
693
Riddle Hsua0536432019-02-16 00:38:59 +0800694 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
695 @Target(ElementType.METHOD)
696 @Retention(RetentionPolicy.SOURCE)
697 @interface HotPath {
698 int NONE = 0;
699 int OOM_ADJUSTMENT = 1;
700 int LRU_UPDATE = 2;
701 int PROCESS_CHANGE = 3;
702 int caller() default NONE;
703 }
704
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800705 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
706 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900707 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800708 mAmInternal.updateOomAdj();
709 }
710 };
711
Charles Chen8d98dd22018-12-26 17:36:54 +0800712 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
713 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700714 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700715 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 mSystemThread = ActivityThread.currentActivityThread();
717 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700718 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800719 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 }
722
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700723 public void onSystemReady() {
724 synchronized (mGlobalLock) {
725 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
726 PackageManager.FEATURE_CANT_SAVE_STATE);
727 mAssistUtils = new AssistUtils(mContext);
728 mVrController.onSystemReady();
729 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700730 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700732 }
733
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700734 public void onInitPowerManagement() {
735 synchronized (mGlobalLock) {
736 mStackSupervisor.initPowerManagement();
737 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
738 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
739 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
740 mVoiceWakeLock.setReferenceCounted(false);
741 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700742 }
743
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700745 mFontScaleSettingObserver = new FontScaleSettingObserver();
746 }
747
Wale Ogunwale59507092018-10-29 09:00:30 -0700748 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700749 final boolean freeformWindowManagement =
750 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
751 || Settings.Global.getInt(
752 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
753
754 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
755 final boolean supportsPictureInPicture = supportsMultiWindow &&
756 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
757 final boolean supportsSplitScreenMultiWindow =
758 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
759 final boolean supportsMultiDisplay = mContext.getPackageManager()
760 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700761 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
762 final boolean forceResizable = Settings.Global.getInt(
763 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700764 final boolean sizeCompatFreeform = Settings.Global.getInt(
765 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766
767 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900768 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769
770 final Configuration configuration = new Configuration();
771 Settings.System.getConfiguration(resolver, configuration);
772 if (forceRtl) {
773 // This will take care of setting the correct layout direction flags
774 configuration.setLayoutDirection(configuration.locale);
775 }
776
777 synchronized (mGlobalLock) {
778 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700779 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700780 final boolean multiWindowFormEnabled = freeformWindowManagement
781 || supportsSplitScreenMultiWindow
782 || supportsPictureInPicture
783 || supportsMultiDisplay;
784 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
785 mSupportsMultiWindow = true;
786 mSupportsFreeformWindowManagement = freeformWindowManagement;
787 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
788 mSupportsPictureInPicture = supportsPictureInPicture;
789 mSupportsMultiDisplay = supportsMultiDisplay;
790 } else {
791 mSupportsMultiWindow = false;
792 mSupportsFreeformWindowManagement = false;
793 mSupportsSplitScreenMultiWindow = false;
794 mSupportsPictureInPicture = false;
795 mSupportsMultiDisplay = false;
796 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700797 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700798 // This happens before any activities are started, so we can change global configuration
799 // in-place.
800 updateConfigurationLocked(configuration, null, true);
801 final Configuration globalConfig = getGlobalConfiguration();
802 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
803
804 // Load resources only after the current configuration has been set.
805 final Resources res = mContext.getResources();
806 mThumbnailWidth = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_width);
808 mThumbnailHeight = res.getDimensionPixelSize(
809 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700810 }
811 }
812
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800813 public WindowManagerGlobalLock getGlobalLock() {
814 return mGlobalLock;
815 }
816
Yunfan Chen585f2932019-01-29 16:04:45 +0900817 /** For test purpose only. */
818 @VisibleForTesting
819 public ActivityTaskManagerInternal getAtmInternal() {
820 return mInternal;
821 }
822
Riddle Hsud93a6c42018-11-29 21:50:06 +0800823 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
824 Looper looper) {
825 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800829 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700830 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700832 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700834 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700836 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700838 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700840 mKeyguardController = mStackSupervisor.getKeyguardController();
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void onActivityManagerInternalAdded() {
844 synchronized (mGlobalLock) {
845 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
846 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
847 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700848 }
849
Yunfan Chen75157d72018-07-27 14:47:21 +0900850 int increaseConfigurationSeqLocked() {
851 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
852 return mConfigurationSeq;
853 }
854
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700855 protected ActivityStackSupervisor createStackSupervisor() {
856 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
857 supervisor.initialize();
858 return supervisor;
859 }
860
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800861 protected AppWarnings createAppWarnings(
862 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
863 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
864 }
865
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700866 public void setWindowManager(WindowManagerService wm) {
867 synchronized (mGlobalLock) {
868 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800870 mTempConfig.setToDefaults();
871 mTempConfig.setLocales(LocaleList.getDefault());
872 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 mLockTaskController.setWindowManager(wm);
875 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700878 }
879
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700880 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
881 synchronized (mGlobalLock) {
882 mUsageStatsInternal = usageStatsManager;
883 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700884 }
885
Wale Ogunwalef6733932018-06-27 05:14:34 -0700886 UserManagerService getUserManager() {
887 if (mUserManager == null) {
888 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
889 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
890 }
891 return mUserManager;
892 }
893
894 AppOpsService getAppOpsService() {
895 if (mAppOpsService == null) {
896 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
897 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
898 }
899 return mAppOpsService;
900 }
901
902 boolean hasUserRestriction(String restriction, int userId) {
903 return getUserManager().hasUserRestriction(restriction, userId);
904 }
905
Michal Karpinski15486842019-04-25 17:33:42 +0100906 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
907 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800908 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100909 if (mode == AppOpsManager.MODE_DEFAULT) {
910 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
911 == PERMISSION_GRANTED;
912 }
913 return mode == AppOpsManager.MODE_ALLOWED;
914 }
915
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700916 @VisibleForTesting
917 protected void setRecentTasks(RecentTasks recentTasks) {
918 mRecentTasks = recentTasks;
919 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700920 }
921
922 RecentTasks getRecentTasks() {
923 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700924 }
925
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700926 ClientLifecycleManager getLifecycleManager() {
927 return mLifecycleManager;
928 }
929
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700930 ActivityStartController getActivityStartController() {
931 return mActivityStartController;
932 }
933
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700934 TaskChangeNotificationController getTaskChangeNotificationController() {
935 return mTaskChangeNotificationController;
936 }
937
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700938 LockTaskController getLockTaskController() {
939 return mLockTaskController;
940 }
941
Yunfan Chen75157d72018-07-27 14:47:21 +0900942 /**
943 * Return the global configuration used by the process corresponding to the input pid. This is
944 * usually the global configuration with some overrides specific to that process.
945 */
946 Configuration getGlobalConfigurationForCallingPid() {
947 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800948 return getGlobalConfigurationForPid(pid);
949 }
950
951 /**
952 * Return the global configuration used by the process corresponding to the given pid.
953 */
954 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900955 if (pid == MY_PID || pid < 0) {
956 return getGlobalConfiguration();
957 }
958 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100959 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 return app != null ? app.getConfiguration() : getGlobalConfiguration();
961 }
962 }
963
964 /**
965 * Return the device configuration info used by the process corresponding to the input pid.
966 * The value is consistent with the global configuration for the process.
967 */
968 @Override
969 public ConfigurationInfo getDeviceConfigurationInfo() {
970 ConfigurationInfo config = new ConfigurationInfo();
971 synchronized (mGlobalLock) {
972 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
973 config.reqTouchScreen = globalConfig.touchscreen;
974 config.reqKeyboardType = globalConfig.keyboard;
975 config.reqNavigation = globalConfig.navigation;
976 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
977 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
978 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
979 }
980 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
981 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
982 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
983 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700984 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900985 }
986 return config;
987 }
988
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700989 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700990 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700991 }
992
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700993 public static final class Lifecycle extends SystemService {
994 private final ActivityTaskManagerService mService;
995
996 public Lifecycle(Context context) {
997 super(context);
998 mService = new ActivityTaskManagerService(context);
999 }
1000
1001 @Override
1002 public void onStart() {
1003 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001004 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001005 }
1006
Garfield Tan891146c2018-10-09 12:14:00 -07001007 @Override
1008 public void onUnlockUser(int userId) {
1009 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001010 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001011 }
1012 }
1013
1014 @Override
1015 public void onCleanupUser(int userId) {
1016 synchronized (mService.getGlobalLock()) {
1017 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1018 }
1019 }
1020
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001021 public ActivityTaskManagerService getService() {
1022 return mService;
1023 }
1024 }
1025
1026 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 public final int startActivity(IApplicationThread caller, String callingPackage,
1028 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1029 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1030 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1031 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1032 UserHandle.getCallingUserId());
1033 }
1034
1035 @Override
1036 public final int startActivities(IApplicationThread caller, String callingPackage,
1037 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1038 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001039 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001041 enforceNotIsolatedCaller(reason);
1042 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001044 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1045 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1046 reason, null /* originatingPendingIntent */,
1047 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001048 }
1049
1050 @Override
1051 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1052 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1053 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1054 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1055 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1056 true /*validateIncomingUser*/);
1057 }
1058
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001059 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1061 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1062 boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001063 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001066 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1068
1069 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001070 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071 .setCaller(caller)
1072 .setCallingPackage(callingPackage)
1073 .setResolvedType(resolvedType)
1074 .setResultTo(resultTo)
1075 .setResultWho(resultWho)
1076 .setRequestCode(requestCode)
1077 .setStartFlags(startFlags)
1078 .setProfilerInfo(profilerInfo)
1079 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001080 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 .execute();
1082
1083 }
1084
1085 @Override
1086 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1087 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001088 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1089 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 // Refuse possible leaked file descriptors
1091 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1092 throw new IllegalArgumentException("File descriptors passed in Intent");
1093 }
1094
1095 if (!(target instanceof PendingIntentRecord)) {
1096 throw new IllegalArgumentException("Bad PendingIntent object");
1097 }
1098
1099 PendingIntentRecord pir = (PendingIntentRecord)target;
1100
1101 synchronized (mGlobalLock) {
1102 // If this is coming from the currently resumed activity, it is
1103 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001104 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 if (stack.mResumedActivity != null &&
1106 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001107 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001108 }
1109 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001110 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001111 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 }
1113
1114 @Override
1115 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1116 Bundle bOptions) {
1117 // Refuse possible leaked file descriptors
1118 if (intent != null && intent.hasFileDescriptors()) {
1119 throw new IllegalArgumentException("File descriptors passed in Intent");
1120 }
1121 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1122
1123 synchronized (mGlobalLock) {
1124 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1125 if (r == null) {
1126 SafeActivityOptions.abort(options);
1127 return false;
1128 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001129 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001130 // The caller is not running... d'oh!
1131 SafeActivityOptions.abort(options);
1132 return false;
1133 }
1134 intent = new Intent(intent);
1135 // The caller is not allowed to change the data.
1136 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1137 // And we are resetting to find the next component...
1138 intent.setComponent(null);
1139
1140 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1141
1142 ActivityInfo aInfo = null;
1143 try {
1144 List<ResolveInfo> resolves =
1145 AppGlobals.getPackageManager().queryIntentActivities(
1146 intent, r.resolvedType,
1147 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1148 UserHandle.getCallingUserId()).getList();
1149
1150 // Look for the original activity in the list...
1151 final int N = resolves != null ? resolves.size() : 0;
1152 for (int i=0; i<N; i++) {
1153 ResolveInfo rInfo = resolves.get(i);
1154 if (rInfo.activityInfo.packageName.equals(r.packageName)
1155 && rInfo.activityInfo.name.equals(r.info.name)) {
1156 // We found the current one... the next matching is
1157 // after it.
1158 i++;
1159 if (i<N) {
1160 aInfo = resolves.get(i).activityInfo;
1161 }
1162 if (debug) {
1163 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1164 + "/" + r.info.name);
1165 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1166 ? "null" : aInfo.packageName + "/" + aInfo.name));
1167 }
1168 break;
1169 }
1170 }
1171 } catch (RemoteException e) {
1172 }
1173
1174 if (aInfo == null) {
1175 // Nobody who is next!
1176 SafeActivityOptions.abort(options);
1177 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1178 return false;
1179 }
1180
1181 intent.setComponent(new ComponentName(
1182 aInfo.applicationInfo.packageName, aInfo.name));
1183 intent.setFlags(intent.getFlags()&~(
1184 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1185 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1186 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1187 FLAG_ACTIVITY_NEW_TASK));
1188
1189 // Okay now we need to start the new activity, replacing the currently running activity.
1190 // This is a little tricky because we want to start the new one as if the current one is
1191 // finished, but not finish the current one first so that there is no flicker.
1192 // And thus...
1193 final boolean wasFinishing = r.finishing;
1194 r.finishing = true;
1195
1196 // Propagate reply information over to the new activity.
1197 final ActivityRecord resultTo = r.resultTo;
1198 final String resultWho = r.resultWho;
1199 final int requestCode = r.requestCode;
1200 r.resultTo = null;
1201 if (resultTo != null) {
1202 resultTo.removeResultsLocked(r, resultWho, requestCode);
1203 }
1204
1205 final long origId = Binder.clearCallingIdentity();
1206 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001207 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001208 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001209 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .setResolvedType(r.resolvedType)
1211 .setActivityInfo(aInfo)
1212 .setResultTo(resultTo != null ? resultTo.appToken : null)
1213 .setResultWho(resultWho)
1214 .setRequestCode(requestCode)
1215 .setCallingPid(-1)
1216 .setCallingUid(r.launchedFromUid)
1217 .setCallingPackage(r.launchedFromPackage)
1218 .setRealCallingPid(-1)
1219 .setRealCallingUid(r.launchedFromUid)
1220 .setActivityOptions(options)
1221 .execute();
1222 Binder.restoreCallingIdentity(origId);
1223
1224 r.finishing = wasFinishing;
1225 if (res != ActivityManager.START_SUCCESS) {
1226 return false;
1227 }
1228 return true;
1229 }
1230 }
1231
1232 @Override
1233 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001236 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001238 enforceNotIsolatedCaller("startActivityAndWait");
1239 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1240 userId, "startActivityAndWait");
1241 // TODO: Switch to user app stacks here.
1242 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1243 .setCaller(caller)
1244 .setCallingPackage(callingPackage)
1245 .setResolvedType(resolvedType)
1246 .setResultTo(resultTo)
1247 .setResultWho(resultWho)
1248 .setRequestCode(requestCode)
1249 .setStartFlags(startFlags)
1250 .setActivityOptions(bOptions)
1251 .setUserId(userId)
1252 .setProfilerInfo(profilerInfo)
1253 .setWaitResult(res)
1254 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 return res;
1256 }
1257
1258 @Override
1259 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1260 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1261 int startFlags, Configuration config, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001262 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001263 enforceNotIsolatedCaller("startActivityWithConfig");
1264 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1265 "startActivityWithConfig");
1266 // TODO: Switch to user app stacks here.
1267 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1268 .setCaller(caller)
1269 .setCallingPackage(callingPackage)
1270 .setResolvedType(resolvedType)
1271 .setResultTo(resultTo)
1272 .setResultWho(resultWho)
1273 .setRequestCode(requestCode)
1274 .setStartFlags(startFlags)
1275 .setGlobalConfiguration(config)
1276 .setActivityOptions(bOptions)
1277 .setUserId(userId)
1278 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 }
1280
Robert Carr8a2f9132019-11-11 15:03:15 -08001281 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1283 int callingUid = Binder.getCallingUid();
1284 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1285 throw new SecurityException("Only the system process can request a permission token, "
1286 + "received request from uid: " + callingUid);
1287 }
1288 IBinder permissionToken = new Binder();
1289 synchronized (mGlobalLock) {
1290 mStartActivitySources.put(permissionToken, delegatorToken);
1291 }
1292
1293 Message expireMsg = PooledLambda.obtainMessage(
1294 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1295 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1296
1297 Message forgetMsg = PooledLambda.obtainMessage(
1298 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1299 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1300
1301 return permissionToken;
1302 }
1303
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 @Override
1305 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1306 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1308 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001310 // permission grants) as any app that may launch one of your own activities. So we only
1311 // allow this in two cases:
1312 // 1) The caller is an activity that is part of the core framework, and then only when it
1313 // is running as the system.
1314 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1315 // can only be requested by a system activity, which may then delegate this call to
1316 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 final ActivityRecord sourceRecord;
1318 final int targetUid;
1319 final String targetPackage;
1320 final boolean isResolver;
1321 synchronized (mGlobalLock) {
1322 if (resultTo == null) {
1323 throw new SecurityException("Must be called from an activity");
1324 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325 final IBinder sourceToken;
1326 if (permissionToken != null) {
1327 // To even attempt to use a permissionToken, an app must also have this signature
1328 // permission.
1329 mAmInternal.enforceCallingPermission(
1330 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1331 "startActivityAsCaller");
1332 // If called with a permissionToken, we want the sourceRecord from the delegator
1333 // activity that requested this token.
1334 sourceToken = mStartActivitySources.remove(permissionToken);
1335 if (sourceToken == null) {
1336 // Invalid permissionToken, check if it recently expired.
1337 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1338 throw new SecurityException("Called with expired permission token: "
1339 + permissionToken);
1340 } else {
1341 throw new SecurityException("Called with invalid permission token: "
1342 + permissionToken);
1343 }
1344 }
1345 } else {
1346 // This method was called directly by the source.
1347 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001349
Louis Chang149d5c82019-12-30 09:47:39 +08001350 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001351 if (sourceRecord == null) {
1352 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 }
1354 if (sourceRecord.app == null) {
1355 throw new SecurityException("Called without a process attached to activity");
1356 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001357
1358 // Whether called directly or from a delegate, the source activity must be from the
1359 // android package.
1360 if (!sourceRecord.info.packageName.equals("android")) {
1361 throw new SecurityException("Must be called from an activity that is "
1362 + "declared in the android package");
1363 }
1364
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001365 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 // This is still okay, as long as this activity is running under the
1367 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001368 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001370 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 + " must be system uid or original calling uid "
1372 + sourceRecord.launchedFromUid);
1373 }
1374 }
1375 if (ignoreTargetSecurity) {
1376 if (intent.getComponent() == null) {
1377 throw new SecurityException(
1378 "Component must be specified with ignoreTargetSecurity");
1379 }
1380 if (intent.getSelector() != null) {
1381 throw new SecurityException(
1382 "Selector not allowed with ignoreTargetSecurity");
1383 }
1384 }
1385 targetUid = sourceRecord.launchedFromUid;
1386 targetPackage = sourceRecord.launchedFromPackage;
1387 isResolver = sourceRecord.isResolverOrChildActivity();
1388 }
1389
1390 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001391 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001392 }
1393
1394 // TODO: Switch to user app stacks here.
1395 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001396 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397 .setCallingUid(targetUid)
1398 .setCallingPackage(targetPackage)
1399 .setResolvedType(resolvedType)
1400 .setResultTo(resultTo)
1401 .setResultWho(resultWho)
1402 .setRequestCode(requestCode)
1403 .setStartFlags(startFlags)
1404 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001405 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1407 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001408 // The target may well be in the background, which would normally prevent it
1409 // from starting an activity. Here we definitely want the start to succeed.
1410 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 .execute();
1412 } catch (SecurityException e) {
1413 // XXX need to figure out how to propagate to original app.
1414 // A SecurityException here is generally actually a fault of the original
1415 // calling activity (such as a fairly granting permissions), so propagate it
1416 // back to them.
1417 /*
1418 StringBuilder msg = new StringBuilder();
1419 msg.append("While launching");
1420 msg.append(intent.toString());
1421 msg.append(": ");
1422 msg.append(e.getMessage());
1423 */
1424 throw e;
1425 }
1426 }
1427
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001428 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1429 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001430 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 }
1432
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 @Override
1434 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1435 Intent intent, String resolvedType, IVoiceInteractionSession session,
1436 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1437 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001438 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001440 if (session == null || interactor == null) {
1441 throw new NullPointerException("null session or interactor");
1442 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001445 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .setCallingUid(callingUid)
1447 .setCallingPackage(callingPackage)
1448 .setResolvedType(resolvedType)
1449 .setVoiceSession(session)
1450 .setVoiceInteractor(interactor)
1451 .setStartFlags(startFlags)
1452 .setProfilerInfo(profilerInfo)
1453 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001454 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001455 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 .execute();
1457 }
1458
1459 @Override
1460 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1461 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001462 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1464 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001466 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 .setCallingUid(callingUid)
1468 .setCallingPackage(callingPackage)
1469 .setResolvedType(resolvedType)
1470 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001471 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001472 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 .execute();
1474 }
1475
Riddle Hsu609a8e22019-06-27 16:46:29 -06001476 /**
1477 * Start the recents activity to perform the recents animation.
1478 *
1479 * @param intent The intent to start the recents activity.
1480 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1481 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001482 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1484 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001485 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001487 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001488 final long origId = Binder.clearCallingIdentity();
1489 try {
1490 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001491 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1492 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001493 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001494
1495 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001496 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001497 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001498 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001499 if (recentsAnimationRunner == null) {
1500 anim.preloadRecentsActivity();
1501 } else {
1502 anim.startRecentsActivity(recentsAnimationRunner);
1503 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 }
1505 } finally {
1506 Binder.restoreCallingIdentity(origId);
1507 }
1508 }
1509
1510 @Override
1511 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001512 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001513 "startActivityFromRecents()");
1514
1515 final int callingPid = Binder.getCallingPid();
1516 final int callingUid = Binder.getCallingUid();
1517 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1518 final long origId = Binder.clearCallingIdentity();
1519 try {
1520 synchronized (mGlobalLock) {
1521 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1522 safeOptions);
1523 }
1524 } finally {
1525 Binder.restoreCallingIdentity(origId);
1526 }
1527 }
1528
1529 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001530 * Public API to check if the client is allowed to start an activity on specified display.
1531 *
1532 * If the target display is private or virtual, some restrictions will apply.
1533 *
1534 * @param displayId Target display id.
1535 * @param intent Intent used to launch the activity.
1536 * @param resolvedType The MIME type of the intent.
1537 * @param userId The id of the user for whom the call is made.
1538 * @return {@code true} if a call to start an activity on the target display should succeed and
1539 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1540 */
1541 @Override
1542 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1543 String resolvedType, int userId) {
1544 final int callingUid = Binder.getCallingUid();
1545 final int callingPid = Binder.getCallingPid();
1546 final long origId = Binder.clearCallingIdentity();
1547
1548 try {
1549 // Collect information about the target of the Intent.
1550 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1551 0 /* startFlags */, null /* profilerInfo */, userId,
1552 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1553 UserHandle.USER_NULL));
1554 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1555
1556 synchronized (mGlobalLock) {
1557 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1558 aInfo);
1559 }
1560 } finally {
1561 Binder.restoreCallingIdentity(origId);
1562 }
1563 }
1564
1565 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 * This is the internal entry point for handling Activity.finish().
1567 *
1568 * @param token The Binder token referencing the Activity we want to finish.
1569 * @param resultCode Result code, if any, from this Activity.
1570 * @param resultData Result data (Intent), if any, from this Activity.
1571 * @param finishTask Whether to finish the task associated with this Activity.
1572 *
1573 * @return Returns true if the activity successfully finished, or false if it is still running.
1574 */
1575 @Override
1576 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1577 int finishTask) {
1578 // Refuse possible leaked file descriptors
1579 if (resultData != null && resultData.hasFileDescriptors()) {
1580 throw new IllegalArgumentException("File descriptors passed in Intent");
1581 }
1582
1583 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001584 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 if (r == null) {
1586 return true;
1587 }
1588 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001589 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001590 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001591 if (rootR == null) {
1592 Slog.w(TAG, "Finishing task with all activities already finished");
1593 }
1594 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1595 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001596 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 return false;
1598 }
1599
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001600 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1601 // We should consolidate.
1602 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001604 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001605 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 if (next != null) {
1607 // ask watcher if this is allowed
1608 boolean resumeOK = true;
1609 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001610 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001612 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 Watchdog.getInstance().setActivityController(null);
1614 }
1615
1616 if (!resumeOK) {
1617 Slog.i(TAG, "Not finishing activity because controller resumed");
1618 return false;
1619 }
1620 }
1621 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001622
1623 // note down that the process has finished an activity and is in background activity
1624 // starts grace period
1625 if (r.app != null) {
1626 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1627 }
1628
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001629 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001630 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001631 try {
1632 boolean res;
1633 final boolean finishWithRootActivity =
1634 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1635 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1636 || (finishWithRootActivity && r == rootR)) {
1637 // If requested, remove the task that is associated to this activity only if it
1638 // was the root activity in the task. The result code and data is ignored
1639 // because we don't support returning them across task boundaries. Also, to
1640 // keep backwards compatibility we remove the task from recents when finishing
1641 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001642 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001644 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001645 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001646 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001647 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001648 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001649 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 if (!res) {
1651 Slog.i(TAG, "Failed to finish by app-request");
1652 }
1653 }
1654 return res;
1655 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001656 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 Binder.restoreCallingIdentity(origId);
1658 }
1659 }
1660 }
1661
1662 @Override
1663 public boolean finishActivityAffinity(IBinder token) {
1664 synchronized (mGlobalLock) {
1665 final long origId = Binder.clearCallingIdentity();
1666 try {
1667 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1668 if (r == null) {
1669 return false;
1670 }
1671
1672 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1673 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001674 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 return false;
1676 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001677
1678 final PooledFunction p = PooledLambda.obtainFunction(
1679 ActivityRecord::finishIfSameAffinity, r,
1680 PooledLambda.__(ActivityRecord.class));
1681 r.getTask().forAllActivities(
1682 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1683 p.recycle();
1684
Andrii Kuliande93eff2019-07-12 12:21:27 -07001685 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 } finally {
1687 Binder.restoreCallingIdentity(origId);
1688 }
1689 }
1690 }
1691
1692 @Override
1693 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1694 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001695 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001696 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001697 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001698 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1699 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001700 return;
1701 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001702 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1703 false /* processPausingActivities */, config);
1704 if (stopProfiling && r.hasProcess()) {
1705 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
1707 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001708 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001709 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001710 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 }
1713
1714 @Override
1715 public final void activityResumed(IBinder token) {
1716 final long origId = Binder.clearCallingIdentity();
1717 synchronized (mGlobalLock) {
1718 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 }
1720 Binder.restoreCallingIdentity(origId);
1721 }
1722
1723 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001724 public final void activityTopResumedStateLost() {
1725 final long origId = Binder.clearCallingIdentity();
1726 synchronized (mGlobalLock) {
1727 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1728 }
1729 Binder.restoreCallingIdentity(origId);
1730 }
1731
1732 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 public final void activityPaused(IBinder token) {
1734 final long origId = Binder.clearCallingIdentity();
1735 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001736 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001737 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1738 if (r != null) {
1739 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001741 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 }
1743 Binder.restoreCallingIdentity(origId);
1744 }
1745
1746 @Override
1747 public final void activityStopped(IBinder token, Bundle icicle,
1748 PersistableBundle persistentState, CharSequence description) {
1749 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1750
1751 // Refuse possible leaked file descriptors
1752 if (icicle != null && icicle.hasFileDescriptors()) {
1753 throw new IllegalArgumentException("File descriptors passed in Bundle");
1754 }
1755
1756 final long origId = Binder.clearCallingIdentity();
1757
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001758 String restartingName = null;
1759 int restartingUid = 0;
1760 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001761 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001762 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001763 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001765 if (r.attachedToProcess()
1766 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1767 // The activity was requested to restart from
1768 // {@link #restartActivityProcessIfVisible}.
1769 restartingName = r.app.mName;
1770 restartingUid = r.app.mUid;
1771 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001772 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 }
1776
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001777 if (restartingName != null) {
1778 // In order to let the foreground activity can be restarted with its saved state from
1779 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1780 // until the activity reports stopped with the state. And the activity record will be
1781 // kept because the record state is restarting, then the activity will be restarted
1782 // immediately if it is still the top one.
1783 mStackSupervisor.removeRestartTimeouts(r);
1784 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1785 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001786 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787
1788 Binder.restoreCallingIdentity(origId);
1789 }
1790
1791 @Override
1792 public final void activityDestroyed(IBinder token) {
1793 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1794 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001795 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001796 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001797 try {
1798 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1799 if (activity != null) {
1800 activity.destroyed("activityDestroyed");
1801 }
1802 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001804 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 }
1806 }
1807 }
1808
1809 @Override
1810 public final void activityRelaunched(IBinder token) {
1811 final long origId = Binder.clearCallingIdentity();
1812 synchronized (mGlobalLock) {
1813 mStackSupervisor.activityRelaunchedLocked(token);
1814 }
1815 Binder.restoreCallingIdentity(origId);
1816 }
1817
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 @Override
1819 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1820 synchronized (mGlobalLock) {
1821 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1822 if (r == null) {
1823 return;
1824 }
1825 final long origId = Binder.clearCallingIdentity();
1826 try {
1827 r.setRequestedOrientation(requestedOrientation);
1828 } finally {
1829 Binder.restoreCallingIdentity(origId);
1830 }
1831 }
1832 }
1833
1834 @Override
1835 public int getRequestedOrientation(IBinder token) {
1836 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001837 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1838 return (r != null)
1839 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001840 }
1841 }
1842
1843 @Override
1844 public void setImmersive(IBinder token, boolean immersive) {
1845 synchronized (mGlobalLock) {
1846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 if (r == null) {
1848 throw new IllegalArgumentException();
1849 }
1850 r.immersive = immersive;
1851
1852 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001853 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001854 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 }
1857 }
1858 }
1859
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001860 void applyUpdateLockStateLocked(ActivityRecord r) {
1861 // Modifications to the UpdateLock state are done on our handler, outside
1862 // the activity manager's locks. The new state is determined based on the
1863 // state *now* of the relevant activity record. The object is passed to
1864 // the handler solely for logging detail, not to be consulted/modified.
1865 final boolean nextState = r != null && r.immersive;
1866 mH.post(() -> {
1867 if (mUpdateLock.isHeld() != nextState) {
1868 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1869 "Applying new update lock state '" + nextState + "' for " + r);
1870 if (nextState) {
1871 mUpdateLock.acquire();
1872 } else {
1873 mUpdateLock.release();
1874 }
1875 }
1876 });
1877 }
1878
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 @Override
1880 public boolean isImmersive(IBinder token) {
1881 synchronized (mGlobalLock) {
1882 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1883 if (r == null) {
1884 throw new IllegalArgumentException();
1885 }
1886 return r.immersive;
1887 }
1888 }
1889
1890 @Override
1891 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001894 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001895 return (r != null) ? r.immersive : false;
1896 }
1897 }
1898
1899 @Override
1900 public void overridePendingTransition(IBinder token, String packageName,
1901 int enterAnim, int exitAnim) {
1902 synchronized (mGlobalLock) {
1903 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1904 if (self == null) {
1905 return;
1906 }
1907
1908 final long origId = Binder.clearCallingIdentity();
1909
1910 if (self.isState(
1911 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001912 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001913 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 }
1915
1916 Binder.restoreCallingIdentity(origId);
1917 }
1918 }
1919
1920 @Override
1921 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001924 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001925 if (r == null) {
1926 return ActivityManager.COMPAT_MODE_UNKNOWN;
1927 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001928 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 }
1931
1932 @Override
1933 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001938 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 if (r == null) {
1940 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1941 return;
1942 }
1943 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001944 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 }
1946 }
1947
1948 @Override
1949 public int getLaunchedFromUid(IBinder activityToken) {
1950 ActivityRecord srec;
1951 synchronized (mGlobalLock) {
1952 srec = ActivityRecord.forTokenLocked(activityToken);
1953 }
1954 if (srec == null) {
1955 return -1;
1956 }
1957 return srec.launchedFromUid;
1958 }
1959
1960 @Override
1961 public String getLaunchedFromPackage(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return null;
1968 }
1969 return srec.launchedFromPackage;
1970 }
1971
1972 @Override
1973 public boolean convertFromTranslucent(IBinder token) {
1974 final long origId = Binder.clearCallingIdentity();
1975 try {
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1978 if (r == null) {
1979 return false;
1980 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001981 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 }
1983 } finally {
1984 Binder.restoreCallingIdentity(origId);
1985 }
1986 }
1987
1988 @Override
1989 public boolean convertToTranslucent(IBinder token, Bundle options) {
1990 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1991 final long origId = Binder.clearCallingIdentity();
1992 try {
1993 synchronized (mGlobalLock) {
1994 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1995 if (r == null) {
1996 return false;
1997 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001998 final ActivityRecord under = r.getTask().getActivityBelow(r);
1999 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002000 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2001 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002002 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 }
2004 } finally {
2005 Binder.restoreCallingIdentity(origId);
2006 }
2007 }
2008
2009 @Override
2010 public void notifyActivityDrawn(IBinder token) {
2011 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2012 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002013 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002015 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002016 }
2017 }
2018 }
2019
2020 @Override
2021 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2022 synchronized (mGlobalLock) {
2023 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2024 if (r == null) {
2025 return;
2026 }
2027 r.reportFullyDrawnLocked(restoredFromBundle);
2028 }
2029 }
2030
2031 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002032 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 synchronized (mGlobalLock) {
2034 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002035 if (stack != null) {
2036 final int displayId = stack.getDisplayId();
2037 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
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 Ogunwale1ebcd8e2020-01-21 11:27:03 -08002051 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
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) {
Louis Chang149d5c82019-12-30 09:47:39 +08002067 final ActivityStack stack = mRootWindowContainer.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 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002072 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002073 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002074 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 }
2076 }
2077 } finally {
2078 Binder.restoreCallingIdentity(callingId);
2079 }
2080 }
2081
2082 @Override
2083 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002089 final Task task = mRootWindowContainer.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")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002096 mRootWindowContainer.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 {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002127 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 "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 Ogunwale1ebcd8e2020-01-21 11:27:03 -08002153 return srec.getRootTask().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) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002166 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002167 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 }
2171 }
2172
2173 /**
2174 * Attempts to move a task backwards in z-order (the order of activities within the task is
2175 * unchanged).
2176 *
2177 * There are several possible results of this call:
2178 * - if the task is locked, then we will show the lock toast
2179 * - if there is a task behind the provided task, then that task is made visible and resumed as
2180 * this task is moved to the back
2181 * - otherwise, if there are no other tasks in the stack:
2182 * - if this task is in the pinned stack, then we remove the stack completely, which will
2183 * have the effect of moving the task to the top or bottom of the fullscreen stack
2184 * (depending on whether it is visible)
2185 * - otherwise, we simply return home and hide this task
2186 *
2187 * @param token A reference to the activity we wish to move
2188 * @param nonRoot If false then this only works if the activity is the root
2189 * of a task; if true it will work for any activity in a task.
2190 * @return Returns true if the move completed, false if not.
2191 */
2192 @Override
2193 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002194 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
2198 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002199 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002201 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 }
2203 } finally {
2204 Binder.restoreCallingIdentity(origId);
2205 }
2206 }
2207 return false;
2208 }
2209
2210 @Override
2211 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002212 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002213 long ident = Binder.clearCallingIdentity();
2214 Rect rect = new Rect();
2215 try {
2216 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002217 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2219 if (task == null) {
2220 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2221 return rect;
2222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002223 if (task.getParent() != null) {
2224 rect.set(task.getBounds());
2225 } else if (task.mLastNonFullscreenBounds != null) {
2226 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 }
2229 } finally {
2230 Binder.restoreCallingIdentity(ident);
2231 }
2232 return rect;
2233 }
2234
2235 @Override
2236 public ActivityManager.TaskDescription getTaskDescription(int id) {
2237 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002238 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002240 final Task tr = mRootWindowContainer.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
Winson Chung7ccc6812020-01-23 16:15:10 -08002250 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002251 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Winson Chung7ccc6812020-01-23 16:15:10 -08002252 return setTaskWindowingModeSplitScreenPrimary(taskId,
2253 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002254 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002255 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002256 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002257 synchronized (mGlobalLock) {
2258 final long ident = Binder.clearCallingIdentity();
2259 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002260 final Task task = mRootWindowContainer.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);
Winson Chung7ccc6812020-01-23 16:15:10 -08002264 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002265 }
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);
Winson Chung7ccc6812020-01-23 16:15:10 -08002281 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002282 } finally {
2283 Binder.restoreCallingIdentity(ident);
2284 }
2285 }
2286 }
2287
2288 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002289 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002290 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 ActivityRecord r = getCallingRecordLocked(token);
2292 return r != null ? r.info.packageName : null;
2293 }
2294 }
2295
2296 @Override
2297 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.intent.getComponent() : null;
2301 }
2302 }
2303
2304 private ActivityRecord getCallingRecordLocked(IBinder token) {
2305 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2306 if (r == null) {
2307 return null;
2308 }
2309 return r.resultTo;
2310 }
2311
2312 @Override
2313 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002314 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315
2316 synchronized (mGlobalLock) {
2317 final long origId = Binder.clearCallingIdentity();
2318 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002319 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 } finally {
2321 Binder.restoreCallingIdentity(origId);
2322 }
2323 }
2324 }
2325
Mark Renouf446251d2019-04-26 10:22:41 -04002326 @Override
2327 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2328 synchronized (mGlobalLock) {
2329 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2330 if (r == null) {
2331 return;
2332 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002333 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002334 if (stack != null && stack.isSingleTaskInstance()) {
2335 // Single-task stacks are used for activities which are presented in floating
2336 // windows above full screen activities. Instead of directly finishing the
2337 // task, a task change listener is used to notify SystemUI so the action can be
2338 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002339 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002340 mTaskChangeNotificationController
2341 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2342 } else {
2343 try {
2344 callback.requestFinish();
2345 } catch (RemoteException e) {
2346 Slog.e(TAG, "Failed to invoke request finish callback", e);
2347 }
2348 }
2349 }
2350 }
2351
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002352 /**
2353 * TODO: Add mController hook
2354 */
2355 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002356 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2357 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002358 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359
2360 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2361 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002362 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2363 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 }
2365 }
2366
Ricky Waiaca8a772019-04-04 16:01:06 +01002367 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2368 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 final int callingPid = Binder.getCallingPid();
2371 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002372 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002373 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 SafeActivityOptions.abort(options);
2375 return;
2376 }
2377 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002378 WindowProcessController callerApp = null;
2379 if (appThread != null) {
2380 callerApp = getProcessController(appThread);
2381 }
2382 final ActivityStarter starter = getActivityStartController().obtainStarter(
2383 null /* intent */, "moveTaskToFront");
2384 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2385 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002386 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 return;
2388 }
2389 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002391 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 if (task == null) {
2393 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002394 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 return;
2396 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002397 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002398 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002399 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 return;
2401 }
2402 ActivityOptions realOptions = options != null
2403 ? options.getOptions(mStackSupervisor)
2404 : null;
2405 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2406 false /* forceNonResizable */);
2407
Wale Ogunwale21e06482019-11-18 05:14:15 -08002408 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 if (topActivity != null) {
2410
2411 // We are reshowing a task, use a starting window to hide the initial draw delay
2412 // so the transition can start earlier.
2413 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2414 true /* taskSwitch */, fromRecents);
2415 }
2416 } finally {
2417 Binder.restoreCallingIdentity(origId);
2418 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 }
2420
Ricky Waiaca8a772019-04-04 16:01:06 +01002421 /**
2422 * Return true if callingUid is system, or packageName belongs to that callingUid.
2423 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002424 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002425 try {
2426 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2427 if (packageName == null) {
2428 return false;
2429 }
2430 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2431 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2432 UserHandle.getUserId(callingUid));
2433 return UserHandle.isSameApp(callingUid, uid);
2434 }
2435 } catch (RemoteException e) {
2436 // Should not happen
2437 }
2438 return true;
2439 }
2440
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002441 /**
2442 * Checks that the provided package name matches the current calling UID, throws a security
2443 * exception if it doesn't.
2444 */
2445 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2446 final int callingUid = Binder.getCallingUid();
2447 if (isSameApp(callingUid, packageName)) {
2448 return;
2449 }
2450 final String msg = "Permission Denial: package=" + packageName
2451 + " does not belong to uid=" + callingUid;
2452 Slog.w(TAG, msg);
2453 throw new SecurityException(msg);
2454 }
2455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2457 int callingPid, int callingUid, String name) {
2458 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2459 return true;
2460 }
2461
2462 if (getRecentTasks().isCallerRecents(sourceUid)) {
2463 return true;
2464 }
2465
2466 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2467 if (perm == PackageManager.PERMISSION_GRANTED) {
2468 return true;
2469 }
2470 if (checkAllowAppSwitchUid(sourceUid)) {
2471 return true;
2472 }
2473
2474 // If the actual IPC caller is different from the logical source, then
2475 // also see if they are allowed to control app switches.
2476 if (callingUid != -1 && callingUid != sourceUid) {
2477 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2478 if (perm == PackageManager.PERMISSION_GRANTED) {
2479 return true;
2480 }
2481 if (checkAllowAppSwitchUid(callingUid)) {
2482 return true;
2483 }
2484 }
2485
2486 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2487 return false;
2488 }
2489
2490 private boolean checkAllowAppSwitchUid(int uid) {
2491 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2492 if (types != null) {
2493 for (int i = types.size() - 1; i >= 0; i--) {
2494 if (types.valueAt(i).intValue() == uid) {
2495 return true;
2496 }
2497 }
2498 }
2499 return false;
2500 }
2501
2502 @Override
2503 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2504 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2505 "setActivityController()");
2506 synchronized (mGlobalLock) {
2507 mController = controller;
2508 mControllerIsAMonkey = imAMonkey;
2509 Watchdog.getInstance().setActivityController(controller);
2510 }
2511 }
2512
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002513 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 synchronized (mGlobalLock) {
2515 return mController != null && mControllerIsAMonkey;
2516 }
2517 }
2518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 @Override
2520 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2521 synchronized (mGlobalLock) {
2522 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2523 }
2524 }
2525
2526 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2528 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2529 }
2530
2531 @Override
2532 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2533 @WindowConfiguration.ActivityType int ignoreActivityType,
2534 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2535 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002536 final int callingPid = Binder.getCallingPid();
2537 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002538 final int[] profileIds = getUserManager().getProfileIds(
2539 UserHandle.getUserId(callingUid), true);
2540 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2541 for (int i = 0; i < profileIds.length; i++) {
2542 callingProfileIds.add(profileIds[i]);
2543 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2545
2546 synchronized (mGlobalLock) {
2547 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2548
Nicholas Sauer0259e532019-08-30 08:24:55 -07002549 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002550 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002551 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 }
2553
2554 return list;
2555 }
2556
2557 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2559 synchronized (mGlobalLock) {
2560 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002561 try {
2562 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2563 if (r == null) return;
2564
2565 final PooledConsumer c = PooledLambda.obtainConsumer(
2566 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2567 r, resultWho, requestCode);
2568 // TODO: This should probably only loop over the task since you need to be in the
2569 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002570 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002571 c.recycle();
2572
2573 updateOomAdj();
2574 } finally {
2575 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 }
2578 }
2579
2580 @Override
2581 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 ActivityStack stack = ActivityRecord.getStackLocked(token);
2584 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002585 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 }
2587 return false;
2588 }
2589 }
2590
2591 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 synchronized (mGlobalLock) {
2595 final long ident = Binder.clearCallingIdentity();
2596 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002597 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 if (task == null) {
2599 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2600 return;
2601 }
2602
2603 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2604 + " to stackId=" + stackId + " toTop=" + toTop);
2605
Louis Chang149d5c82019-12-30 09:47:39 +08002606 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 if (stack == null) {
2608 throw new IllegalStateException(
2609 "moveTaskToStack: No stack for stackId=" + stackId);
2610 }
2611 if (!stack.isActivityTypeStandardOrUndefined()) {
2612 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2613 + taskId + " to stack " + stackId);
2614 }
2615 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002616 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2618 }
2619 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2620 "moveTaskToStack");
2621 } finally {
2622 Binder.restoreCallingIdentity(ident);
2623 }
2624 }
2625 }
2626
2627 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002628 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2629 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002630
2631 final long ident = Binder.clearCallingIdentity();
2632 try {
2633 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002634 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002635 if (stack == null) {
2636 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2637 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002639 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2640 throw new IllegalArgumentException("Stack: " + stackId
2641 + " doesn't support animated resize.");
2642 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002643 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002644 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645 }
2646 } finally {
2647 Binder.restoreCallingIdentity(ident);
2648 }
2649 }
2650
wilsonshih5c4cf522019-01-25 09:03:47 +08002651 @Override
2652 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2653 int animationDuration) {
2654 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2655
2656 final long ident = Binder.clearCallingIdentity();
2657 try {
2658 synchronized (mGlobalLock) {
2659 if (xOffset == 0 && yOffset == 0) {
2660 return;
2661 }
Louis Chang149d5c82019-12-30 09:47:39 +08002662 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002663 if (stack == null) {
2664 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2665 return;
2666 }
2667 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2668 throw new IllegalArgumentException("Stack: " + stackId
2669 + " doesn't support animated resize.");
2670 }
2671 final Rect destBounds = new Rect();
2672 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002673 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002674 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2675 return;
2676 }
2677 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002678 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002679 animationDuration, false /* fromFullscreen */);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 /**
2686 * Moves the specified task to the primary-split-screen stack.
2687 *
2688 * @param taskId Id of task to move.
2689 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2690 * exist already. See
2691 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2692 * and
2693 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2694 * @param toTop If the task and stack should be moved to the top.
2695 * @param animate Whether we should play an animation for the moving the task.
2696 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2697 * stack. Pass {@code null} to use default bounds.
2698 * @param showRecents If the recents activity should be shown on the other side of the task
2699 * going into split-screen mode.
Winson Chung7ccc6812020-01-23 16:15:10 -08002700 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 */
2702 @Override
2703 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2704 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002705 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 "setTaskWindowingModeSplitScreenPrimary()");
2707 synchronized (mGlobalLock) {
2708 final long ident = Binder.clearCallingIdentity();
2709 try {
Winson Chung7ccc6812020-01-23 16:15:10 -08002710 if (isInLockTaskMode()) {
2711 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: Is in lock task mode="
2712 + getLockTaskModeState());
2713 return false;
2714 }
2715
Louis Chang149d5c82019-12-30 09:47:39 +08002716 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002717 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002718 if (task == null) {
2719 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2720 return false;
2721 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002722 if (!task.isActivityTypeStandardOrUndefined()) {
2723 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2724 + " non-standard task " + taskId + " to split-screen windowing mode");
2725 }
2726
Winson Chung7ccc6812020-01-23 16:15:10 -08002727 if (DEBUG_STACK) Slog.d(TAG_STACK,
2728 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2729 + " to createMode=" + createMode + " toTop=" + toTop);
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002730 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 final int windowingMode = task.getWindowingMode();
2732 final ActivityStack stack = task.getStack();
2733 if (toTop) {
2734 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2735 }
2736 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002737 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2738 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002739 return windowingMode != task.getWindowingMode();
2740 } finally {
2741 Binder.restoreCallingIdentity(ident);
2742 }
2743 }
2744 }
2745
2746 /**
2747 * Removes stacks in the input windowing modes from the system if they are of activity type
2748 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2749 */
2750 @Override
2751 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002752 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002753 "removeStacksInWindowingModes()");
2754
2755 synchronized (mGlobalLock) {
2756 final long ident = Binder.clearCallingIdentity();
2757 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002758 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002759 } finally {
2760 Binder.restoreCallingIdentity(ident);
2761 }
2762 }
2763 }
2764
2765 @Override
2766 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002767 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002768 "removeStacksWithActivityTypes()");
2769
2770 synchronized (mGlobalLock) {
2771 final long ident = Binder.clearCallingIdentity();
2772 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002773 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002774 } finally {
2775 Binder.restoreCallingIdentity(ident);
2776 }
2777 }
2778 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779
2780 @Override
2781 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2782 int userId) {
2783 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2785 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002787 final boolean detailed = checkGetTasksPermission(
2788 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2789 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 == PackageManager.PERMISSION_GRANTED;
2791
2792 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002793 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 callingUid);
2795 }
2796 }
2797
2798 @Override
2799 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002800 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 long ident = Binder.clearCallingIdentity();
2802 try {
2803 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002804 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 }
2806 } finally {
2807 Binder.restoreCallingIdentity(ident);
2808 }
2809 }
2810
2811 @Override
2812 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002813 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 long ident = Binder.clearCallingIdentity();
2815 try {
2816 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002817 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 }
2819 } finally {
2820 Binder.restoreCallingIdentity(ident);
2821 }
2822 }
2823
2824 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002825 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2826 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2827 long ident = Binder.clearCallingIdentity();
2828 try {
2829 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002830 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002831 }
2832 } finally {
2833 Binder.restoreCallingIdentity(ident);
2834 }
2835 }
2836
2837 @Override
2838 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2839 int displayId) {
2840 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2841 long ident = Binder.clearCallingIdentity();
2842 try {
2843 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002844 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002845 }
2846 } finally {
2847 Binder.restoreCallingIdentity(ident);
2848 }
2849 }
2850
2851 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 final long callingUid = Binder.getCallingUid();
2855 final long origId = Binder.clearCallingIdentity();
2856 try {
2857 synchronized (mGlobalLock) {
2858 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002859 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2861 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2862 }
2863 } finally {
2864 Binder.restoreCallingIdentity(origId);
2865 }
2866 }
2867
2868 @Override
2869 public void startLockTaskModeByToken(IBinder token) {
2870 synchronized (mGlobalLock) {
2871 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2872 if (r == null) {
2873 return;
2874 }
Louis Changcdec0802019-11-11 11:45:07 +08002875 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 }
2877 }
2878
2879 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002880 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002881 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002882 // This makes inner call to look as if it was initiated by system.
2883 long ident = Binder.clearCallingIdentity();
2884 try {
2885 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002886 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002887 MATCH_TASK_IN_STACKS_ONLY);
2888 if (task == null) {
2889 return;
2890 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891
2892 // When starting lock task mode the stack must be in front and focused
2893 task.getStack().moveToFront("startSystemLockTaskMode");
2894 startLockTaskModeLocked(task, true /* isSystemCaller */);
2895 }
2896 } finally {
2897 Binder.restoreCallingIdentity(ident);
2898 }
2899 }
2900
2901 @Override
2902 public void stopLockTaskModeByToken(IBinder token) {
2903 synchronized (mGlobalLock) {
2904 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2905 if (r == null) {
2906 return;
2907 }
Louis Changcdec0802019-11-11 11:45:07 +08002908 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 }
2910 }
2911
2912 /**
2913 * This API should be called by SystemUI only when user perform certain action to dismiss
2914 * lock task mode. We should only dismiss pinned lock task mode in this case.
2915 */
2916 @Override
2917 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002918 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2920 }
2921
Louis Changcdec0802019-11-11 11:45:07 +08002922 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2924 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2925 return;
2926 }
2927
Louis Chang149d5c82019-12-30 09:47:39 +08002928 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002929 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 throw new IllegalArgumentException("Invalid task, not in foreground");
2931 }
2932
2933 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2934 // system or a specific app.
2935 // * System-initiated requests will only start the pinned mode (screen pinning)
2936 // * App-initiated requests
2937 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2938 // - will start the pinned mode, otherwise
2939 final int callingUid = Binder.getCallingUid();
2940 long ident = Binder.clearCallingIdentity();
2941 try {
2942 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002943 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002945 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 } finally {
2947 Binder.restoreCallingIdentity(ident);
2948 }
2949 }
2950
Louis Changcdec0802019-11-11 11:45:07 +08002951 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 final int callingUid = Binder.getCallingUid();
2953 long ident = Binder.clearCallingIdentity();
2954 try {
2955 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002956 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 }
2958 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2959 // task and jumping straight into a call in the case of emergency call back.
2960 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2961 if (tm != null) {
2962 tm.showInCallScreen(false);
2963 }
2964 } finally {
2965 Binder.restoreCallingIdentity(ident);
2966 }
2967 }
2968
2969 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002970 public void updateLockTaskPackages(int userId, String[] packages) {
2971 final int callingUid = Binder.getCallingUid();
2972 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2973 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2974 "updateLockTaskPackages()");
2975 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002976 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002977 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2978 + Arrays.toString(packages));
2979 getLockTaskController().updateLockTaskPackages(userId, packages);
2980 }
2981 }
2982
2983 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 public boolean isInLockTaskMode() {
2985 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2986 }
2987
2988 @Override
2989 public int getLockTaskModeState() {
2990 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002991 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2997 synchronized (mGlobalLock) {
2998 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2999 if (r != null) {
3000 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003001 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003002 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 }
3004 }
3005 }
3006
3007 @Override
3008 public Bundle getActivityOptions(IBinder token) {
3009 final long origId = Binder.clearCallingIdentity();
3010 try {
3011 synchronized (mGlobalLock) {
3012 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3013 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003014 final ActivityOptions activityOptions = r.takeOptionsLocked(
3015 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 return activityOptions == null ? null : activityOptions.toBundle();
3017 }
3018 return null;
3019 }
3020 } finally {
3021 Binder.restoreCallingIdentity(origId);
3022 }
3023 }
3024
3025 @Override
3026 public List<IBinder> getAppTasks(String callingPackage) {
3027 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003028 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 long ident = Binder.clearCallingIdentity();
3030 try {
3031 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003032 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 }
3034 } finally {
3035 Binder.restoreCallingIdentity(ident);
3036 }
3037 }
3038
3039 @Override
3040 public void finishVoiceTask(IVoiceInteractionSession session) {
3041 synchronized (mGlobalLock) {
3042 final long origId = Binder.clearCallingIdentity();
3043 try {
3044 // TODO: VI Consider treating local voice interactions and voice tasks
3045 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003046 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 } finally {
3048 Binder.restoreCallingIdentity(origId);
3049 }
3050 }
3051
3052 }
3053
3054 @Override
3055 public boolean isTopOfTask(IBinder token) {
3056 synchronized (mGlobalLock) {
3057 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003058 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003059 }
3060 }
3061
3062 @Override
3063 public void notifyLaunchTaskBehindComplete(IBinder token) {
3064 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3065 }
3066
3067 @Override
3068 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003069 mH.post(() -> {
3070 synchronized (mGlobalLock) {
3071 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003072 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003073 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003074 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003075 } catch (RemoteException e) {
3076 }
3077 }
3078 }
3079
3080 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 }
3082
3083 /** Called from an app when assist data is ready. */
3084 @Override
3085 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3086 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003087 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003088 synchronized (pae) {
3089 pae.result = extras;
3090 pae.structure = structure;
3091 pae.content = content;
3092 if (referrer != null) {
3093 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3094 }
3095 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003096 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003097 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003098 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 structure.setHomeActivity(pae.isHome);
3100 }
3101 pae.haveResult = true;
3102 pae.notifyAll();
3103 if (pae.intent == null && pae.receiver == null) {
3104 // Caller is just waiting for the result.
3105 return;
3106 }
3107 }
3108 // We are now ready to launch the assist activity.
3109 IAssistDataReceiver sendReceiver = null;
3110 Bundle sendBundle = null;
3111 synchronized (mGlobalLock) {
3112 buildAssistBundleLocked(pae, extras);
3113 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003114 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 if (!exists) {
3116 // Timed out.
3117 return;
3118 }
3119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 // Caller wants result sent back to them.
3122 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003123 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003124 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003125 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3126 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3128 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3129 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3130 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3131 }
3132 }
3133 if (sendReceiver != null) {
3134 try {
3135 sendReceiver.onHandleAssistData(sendBundle);
3136 } catch (RemoteException e) {
3137 }
3138 return;
3139 }
3140
3141 final long ident = Binder.clearCallingIdentity();
3142 try {
3143 if (TextUtils.equals(pae.intent.getAction(),
3144 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003145 // Start voice interaction through VoiceInteractionManagerService.
3146 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3147 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 } else {
3149 pae.intent.replaceExtras(pae.extras);
3150 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3151 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3152 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003153 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154
3155 try {
3156 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3157 } catch (ActivityNotFoundException e) {
3158 Slog.w(TAG, "No activity to handle assist action.", e);
3159 }
3160 }
3161 } finally {
3162 Binder.restoreCallingIdentity(ident);
3163 }
3164 }
3165
3166 @Override
3167 public int addAppTask(IBinder activityToken, Intent intent,
3168 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3169 final int callingUid = Binder.getCallingUid();
3170 final long callingIdent = Binder.clearCallingIdentity();
3171
3172 try {
3173 synchronized (mGlobalLock) {
3174 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3175 if (r == null) {
3176 throw new IllegalArgumentException("Activity does not exist; token="
3177 + activityToken);
3178 }
3179 ComponentName comp = intent.getComponent();
3180 if (comp == null) {
3181 throw new IllegalArgumentException("Intent " + intent
3182 + " must specify explicit component");
3183 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 if (thumbnail.getWidth() != mThumbnailWidth
3185 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 throw new IllegalArgumentException("Bad thumbnail size: got "
3187 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 }
3190 if (intent.getSelector() != null) {
3191 intent.setSelector(null);
3192 }
3193 if (intent.getSourceBounds() != null) {
3194 intent.setSourceBounds(null);
3195 }
3196 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3197 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3198 // The caller has added this as an auto-remove task... that makes no
3199 // sense, so turn off auto-remove.
3200 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3201 }
3202 }
3203 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3204 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3205 if (ainfo.applicationInfo.uid != callingUid) {
3206 throw new SecurityException(
3207 "Can't add task for another application: target uid="
3208 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3209 }
3210
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003211 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003212 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003213 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003214 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003215 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003216 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 return INVALID_TASK_ID;
3218 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003219 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220
3221 // TODO: Send the thumbnail to WM to store it.
3222
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003223 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 }
3225 } finally {
3226 Binder.restoreCallingIdentity(callingIdent);
3227 }
3228 }
3229
3230 @Override
3231 public Point getAppTaskThumbnailSize() {
3232 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003233 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 }
3235 }
3236
3237 @Override
3238 public void setTaskResizeable(int taskId, int resizeableMode) {
3239 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003240 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3242 if (task == null) {
3243 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3244 return;
3245 }
3246 task.setResizeMode(resizeableMode);
3247 }
3248 }
3249
3250 @Override
3251 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003252 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 long ident = Binder.clearCallingIdentity();
3254 try {
3255 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003256 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003257 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258 if (task == null) {
3259 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3260 return;
3261 }
3262 // Place the task in the right stack if it isn't there already based on
3263 // the requested bounds.
3264 // The stack transition logic is:
3265 // - a null bounds on a freeform task moves that task to fullscreen
3266 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3267 // that task to freeform
3268 // - otherwise the task is not moved
3269 ActivityStack stack = task.getStack();
3270 if (!task.getWindowConfiguration().canResizeTask()) {
3271 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3272 }
3273 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3274 stack = stack.getDisplay().getOrCreateStack(
3275 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3276 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3277 stack = stack.getDisplay().getOrCreateStack(
3278 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3279 }
3280
3281 // Reparent the task to the right stack if necessary
3282 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3283 if (stack != task.getStack()) {
3284 // Defer resume until the task is resized below
3285 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3286 DEFER_RESUME, "resizeTask");
3287 preserveWindow = false;
3288 }
3289
3290 // After reparenting (which only resizes the task to the stack bounds), resize the
3291 // task to the actual bounds provided
3292 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3293 }
3294 } finally {
3295 Binder.restoreCallingIdentity(ident);
3296 }
3297 }
3298
3299 @Override
3300 public boolean releaseActivityInstance(IBinder token) {
3301 synchronized (mGlobalLock) {
3302 final long origId = Binder.clearCallingIdentity();
3303 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003304 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3305 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003306 return false;
3307 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003308 r.destroyImmediately(true /* removeFromApp */, "app-req");
3309 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 } finally {
3311 Binder.restoreCallingIdentity(origId);
3312 }
3313 }
3314 }
3315
3316 @Override
3317 public void releaseSomeActivities(IApplicationThread appInt) {
3318 synchronized (mGlobalLock) {
3319 final long origId = Binder.clearCallingIdentity();
3320 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003321 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003322 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 } finally {
3324 Binder.restoreCallingIdentity(origId);
3325 }
3326 }
3327 }
3328
3329 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003330 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 != PackageManager.PERMISSION_GRANTED) {
3333 throw new SecurityException("Requires permission "
3334 + android.Manifest.permission.DEVICE_POWER);
3335 }
3336
3337 synchronized (mGlobalLock) {
3338 long ident = Binder.clearCallingIdentity();
3339 if (mKeyguardShown != keyguardShowing) {
3340 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003341 final Message msg = PooledLambda.obtainMessage(
3342 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3343 keyguardShowing);
3344 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 }
3346 try {
wilsonshih177261f2019-02-22 12:02:18 +08003347 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 } finally {
3349 Binder.restoreCallingIdentity(ident);
3350 }
3351 }
3352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003353 mH.post(() -> {
3354 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3355 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3356 }
3357 });
3358 }
3359
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003360 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003361 mH.post(() -> {
3362 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3363 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3364 }
3365 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 }
3367
3368 @Override
3369 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3371 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372
3373 final File passedIconFile = new File(filePath);
3374 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3375 passedIconFile.getName());
3376 if (!legitIconFile.getPath().equals(filePath)
3377 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3378 throw new IllegalArgumentException("Bad file path: " + filePath
3379 + " passed for userId " + userId);
3380 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003381 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 }
3383
3384 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003386 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 synchronized (mGlobalLock) {
3388 final long ident = Binder.clearCallingIdentity();
3389 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003390 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 if (stack == null) {
3392 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3393 return;
3394 }
3395 if (!stack.isActivityTypeStandardOrUndefined()) {
3396 throw new IllegalArgumentException(
3397 "Removing non-standard stack is not allowed.");
3398 }
3399 mStackSupervisor.removeStack(stack);
3400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
3403 }
3404 }
3405
3406 @Override
3407 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003409
3410 synchronized (mGlobalLock) {
3411 final long ident = Binder.clearCallingIdentity();
3412 try {
3413 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3414 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003415 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 } finally {
3417 Binder.restoreCallingIdentity(ident);
3418 }
3419 }
3420 }
3421
3422 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003423 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 synchronized (mGlobalLock) {
3425 long ident = Binder.clearCallingIdentity();
3426 try {
3427 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3428 if (r == null) {
3429 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003430 "toggleFreeformWindowingMode: No activity record matching token="
3431 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003434 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003435 if (stack == null) {
3436 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3437 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 }
3439
Yunfan Chend967af82019-01-17 18:30:18 +09003440 if (!stack.inFreeformWindowingMode()
3441 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3442 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3443 + "toggle between fullscreen and freeform.");
3444 }
3445
3446 if (stack.inFreeformWindowingMode()) {
3447 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003448 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003449 throw new IllegalStateException("Size-compat windows are currently not"
3450 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003451 } else if (stack.getParent().inFreeformWindowingMode()) {
3452 // If the window is on a freeform display, set it to undefined. It will be
3453 // resolved to freeform and it can adjust windowing mode when the display mode
3454 // changes in runtime.
3455 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003456 } else {
3457 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3458 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 } finally {
3460 Binder.restoreCallingIdentity(ident);
3461 }
3462 }
3463 }
3464
3465 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3466 @Override
3467 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003468 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003470 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 }
3472
3473 /** Unregister a task stack listener so that it stops receiving callbacks. */
3474 @Override
3475 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003476 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003477 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003478 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 }
3480
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 @Override
3482 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3483 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3484 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3485 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3486 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3487 }
3488
3489 @Override
3490 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3491 IBinder activityToken, int flags) {
3492 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3493 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3494 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3495 }
3496
3497 @Override
3498 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3499 Bundle args) {
3500 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3501 true /* focused */, true /* newSessionId */, userHandle, args,
3502 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3503 }
3504
3505 @Override
3506 public Bundle getAssistContextExtras(int requestType) {
3507 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3508 null, null, true /* focused */, true /* newSessionId */,
3509 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3510 if (pae == null) {
3511 return null;
3512 }
3513 synchronized (pae) {
3514 while (!pae.haveResult) {
3515 try {
3516 pae.wait();
3517 } catch (InterruptedException e) {
3518 }
3519 }
3520 }
3521 synchronized (mGlobalLock) {
3522 buildAssistBundleLocked(pae, pae.result);
3523 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003524 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 }
3526 return pae.extras;
3527 }
3528
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003529 /**
3530 * Binder IPC calls go through the public entry point.
3531 * This can be called with or without the global lock held.
3532 */
3533 private static int checkCallingPermission(String permission) {
3534 return checkPermission(
3535 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3536 }
3537
3538 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003539 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003540 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3541 mAmInternal.enforceCallingPermission(permission, func);
3542 }
3543 }
3544
3545 @VisibleForTesting
3546 int checkGetTasksPermission(String permission, int pid, int uid) {
3547 return checkPermission(permission, pid, uid);
3548 }
3549
3550 static int checkPermission(String permission, int pid, int uid) {
3551 if (permission == null) {
3552 return PackageManager.PERMISSION_DENIED;
3553 }
3554 return checkComponentPermission(permission, pid, uid, -1, true);
3555 }
3556
Wale Ogunwale214f3482018-10-04 11:00:47 -07003557 public static int checkComponentPermission(String permission, int pid, int uid,
3558 int owningUid, boolean exported) {
3559 return ActivityManagerService.checkComponentPermission(
3560 permission, pid, uid, owningUid, exported);
3561 }
3562
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003563 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3564 if (getRecentTasks().isCallerRecents(callingUid)) {
3565 // Always allow the recents component to get tasks
3566 return true;
3567 }
3568
3569 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3570 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3571 if (!allowed) {
3572 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3573 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3574 // Temporary compatibility: some existing apps on the system image may
3575 // still be requesting the old permission and not switched to the new
3576 // one; if so, we'll still allow them full access. This means we need
3577 // to see if they are holding the old permission and are a system app.
3578 try {
3579 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3580 allowed = true;
3581 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3582 + " is using old GET_TASKS but privileged; allowing");
3583 }
3584 } catch (RemoteException e) {
3585 }
3586 }
3587 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3588 + " does not hold REAL_GET_TASKS; limiting output");
3589 }
3590 return allowed;
3591 }
3592
Nicholas Sauer0259e532019-08-30 08:24:55 -07003593 boolean isCrossUserAllowed(int pid, int uid) {
3594 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3595 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3596 }
3597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3599 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3600 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3601 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003602 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 "enqueueAssistContext()");
3604
3605 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003606 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 if (activity == null) {
3608 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3609 return null;
3610 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003611 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3613 return null;
3614 }
3615 if (focused) {
3616 if (activityToken != null) {
3617 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3618 if (activity != caller) {
3619 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3620 + " is not current top " + activity);
3621 return null;
3622 }
3623 }
3624 } else {
3625 activity = ActivityRecord.forTokenLocked(activityToken);
3626 if (activity == null) {
3627 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3628 + " couldn't be found");
3629 return null;
3630 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003631 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3633 return null;
3634 }
3635 }
3636
3637 PendingAssistExtras pae;
3638 Bundle extras = new Bundle();
3639 if (args != null) {
3640 extras.putAll(args);
3641 }
3642 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003643 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644
3645 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3646 userHandle);
3647 pae.isHome = activity.isActivityTypeHome();
3648
3649 // Increment the sessionId if necessary
3650 if (newSessionId) {
3651 mViSessionId++;
3652 }
3653 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003654 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3655 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003657 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 } catch (RemoteException e) {
3659 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3660 return null;
3661 }
3662 return pae;
3663 }
3664 }
3665
3666 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3667 if (result != null) {
3668 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3669 }
3670 if (pae.hint != null) {
3671 pae.extras.putBoolean(pae.hint, true);
3672 }
3673 }
3674
3675 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3676 IAssistDataReceiver receiver;
3677 synchronized (mGlobalLock) {
3678 mPendingAssistExtras.remove(pae);
3679 receiver = pae.receiver;
3680 }
3681 if (receiver != null) {
3682 // Caller wants result sent back to them.
3683 Bundle sendBundle = new Bundle();
3684 // At least return the receiver extras
3685 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3686 try {
3687 pae.receiver.onHandleAssistData(sendBundle);
3688 } catch (RemoteException e) {
3689 }
3690 }
3691 }
3692
3693 public class PendingAssistExtras extends Binder implements Runnable {
3694 public final ActivityRecord activity;
3695 public boolean isHome;
3696 public final Bundle extras;
3697 public final Intent intent;
3698 public final String hint;
3699 public final IAssistDataReceiver receiver;
3700 public final int userHandle;
3701 public boolean haveResult = false;
3702 public Bundle result = null;
3703 public AssistStructure structure = null;
3704 public AssistContent content = null;
3705 public Bundle receiverExtras;
3706
3707 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3708 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3709 int _userHandle) {
3710 activity = _activity;
3711 extras = _extras;
3712 intent = _intent;
3713 hint = _hint;
3714 receiver = _receiver;
3715 receiverExtras = _receiverExtras;
3716 userHandle = _userHandle;
3717 }
3718
3719 @Override
3720 public void run() {
3721 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3722 synchronized (this) {
3723 haveResult = true;
3724 notifyAll();
3725 }
3726 pendingAssistExtrasTimedOut(this);
3727 }
3728 }
3729
3730 @Override
3731 public boolean isAssistDataAllowedOnCurrentActivity() {
3732 int userId;
3733 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003734 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3736 return false;
3737 }
3738
Wale Ogunwale21e06482019-11-18 05:14:15 -08003739 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 if (activity == null) {
3741 return false;
3742 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003743 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 }
3745 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3746 }
3747
3748 @Override
3749 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3750 long ident = Binder.clearCallingIdentity();
3751 try {
3752 synchronized (mGlobalLock) {
3753 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003754 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 if (top != caller) {
3756 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3757 + " is not current top " + top);
3758 return false;
3759 }
3760 if (!top.nowVisible) {
3761 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3762 + " is not visible");
3763 return false;
3764 }
3765 }
3766 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3767 token);
3768 } finally {
3769 Binder.restoreCallingIdentity(ident);
3770 }
3771 }
3772
3773 @Override
3774 public boolean isRootVoiceInteraction(IBinder token) {
3775 synchronized (mGlobalLock) {
3776 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3777 if (r == null) {
3778 return false;
3779 }
3780 return r.rootVoiceInteraction;
3781 }
3782 }
3783
Wale Ogunwalef6733932018-06-27 05:14:34 -07003784 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3785 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3786 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3787 if (activityToCallback == null) return;
3788 activityToCallback.setVoiceSessionLocked(voiceSession);
3789
3790 // Inform the activity
3791 try {
3792 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3793 voiceInteractor);
3794 long token = Binder.clearCallingIdentity();
3795 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003796 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003797 } finally {
3798 Binder.restoreCallingIdentity(token);
3799 }
3800 // TODO: VI Should we cache the activity so that it's easier to find later
3801 // rather than scan through all the stacks and activities?
3802 } catch (RemoteException re) {
3803 activityToCallback.clearVoiceSessionLocked();
3804 // TODO: VI Should this terminate the voice session?
3805 }
3806 }
3807
3808 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3809 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3810 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3811 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3812 boolean wasRunningVoice = mRunningVoice != null;
3813 mRunningVoice = session;
3814 if (!wasRunningVoice) {
3815 mVoiceWakeLock.acquire();
3816 updateSleepIfNeededLocked();
3817 }
3818 }
3819 }
3820
3821 void finishRunningVoiceLocked() {
3822 if (mRunningVoice != null) {
3823 mRunningVoice = null;
3824 mVoiceWakeLock.release();
3825 updateSleepIfNeededLocked();
3826 }
3827 }
3828
3829 @Override
3830 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3831 synchronized (mGlobalLock) {
3832 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3833 if (keepAwake) {
3834 mVoiceWakeLock.acquire();
3835 } else {
3836 mVoiceWakeLock.release();
3837 }
3838 }
3839 }
3840 }
3841
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842 @Override
3843 public ComponentName getActivityClassForToken(IBinder token) {
3844 synchronized (mGlobalLock) {
3845 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3846 if (r == null) {
3847 return null;
3848 }
3849 return r.intent.getComponent();
3850 }
3851 }
3852
3853 @Override
3854 public String getPackageForToken(IBinder token) {
3855 synchronized (mGlobalLock) {
3856 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3857 if (r == null) {
3858 return null;
3859 }
3860 return r.packageName;
3861 }
3862 }
3863
3864 @Override
3865 public void showLockTaskEscapeMessage(IBinder token) {
3866 synchronized (mGlobalLock) {
3867 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3868 if (r == null) {
3869 return;
3870 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003871 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 }
3873 }
3874
3875 @Override
3876 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003877 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 final long token = Binder.clearCallingIdentity();
3879 try {
3880 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003881 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 }
3883 } finally {
3884 Binder.restoreCallingIdentity(token);
3885 }
3886 }
3887
3888 /**
3889 * Try to place task to provided position. The final position might be different depending on
3890 * current user and stacks state. The task will be moved to target stack if it's currently in
3891 * different stack.
3892 */
3893 @Override
3894 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003895 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 synchronized (mGlobalLock) {
3897 long ident = Binder.clearCallingIdentity();
3898 try {
3899 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3900 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003901 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003902 if (task == null) {
3903 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3904 + taskId);
3905 }
3906
Louis Chang149d5c82019-12-30 09:47:39 +08003907 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908
3909 if (stack == null) {
3910 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3911 + stackId);
3912 }
3913 if (!stack.isActivityTypeStandardOrUndefined()) {
3914 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3915 + " the position of task " + taskId + " in/to non-standard stack");
3916 }
3917
3918 // TODO: Have the callers of this API call a separate reparent method if that is
3919 // what they intended to do vs. having this method also do reparenting.
3920 if (task.getStack() == stack) {
3921 // Change position in current stack.
3922 stack.positionChildAt(task, position);
3923 } else {
3924 // Reparent to new stack.
3925 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3926 !DEFER_RESUME, "positionTaskInStack");
3927 }
3928 } finally {
3929 Binder.restoreCallingIdentity(ident);
3930 }
3931 }
3932 }
3933
3934 @Override
3935 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3936 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3937 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003938 + Arrays.toString(horizontalSizeConfiguration) + " "
3939 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 synchronized (mGlobalLock) {
3941 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3942 if (record == null) {
3943 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3944 + "found for: " + token);
3945 }
3946 record.setSizeConfigurations(horizontalSizeConfiguration,
3947 verticalSizeConfigurations, smallestSizeConfigurations);
3948 }
3949 }
3950
3951 /**
3952 * Dismisses split-screen multi-window mode.
3953 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3954 */
3955 @Override
3956 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003957 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3959 final long ident = Binder.clearCallingIdentity();
3960 try {
3961 synchronized (mGlobalLock) {
3962 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08003963 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003964 if (stack == null) {
3965 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3966 return;
3967 }
3968
3969 if (toTop) {
3970 // Caller wants the current split-screen primary stack to be the top stack after
3971 // it goes fullscreen, so move it to the front.
3972 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003973 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003975 // stack after it goes fullscreen, so we move the focus to the top-most
3976 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3978 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3979 if (otherStack != null) {
3980 otherStack.moveToFront("dismissSplitScreenMode_other");
3981 }
3982 }
3983
Evan Rosky10475742018-09-05 19:02:48 -07003984 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 }
3986 } finally {
3987 Binder.restoreCallingIdentity(ident);
3988 }
3989 }
3990
3991 /**
3992 * Dismisses Pip
3993 * @param animate True if the dismissal should be animated.
3994 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3995 * default animation duration should be used.
3996 */
3997 @Override
3998 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003999 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 final long ident = Binder.clearCallingIdentity();
4001 try {
4002 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004003 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004004 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 if (stack == null) {
4006 Slog.w(TAG, "dismissPip: pinned stack not found.");
4007 return;
4008 }
4009 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4010 throw new IllegalArgumentException("Stack: " + stack
4011 + " doesn't support animated resize.");
4012 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004013 /**
4014 * TODO(b/146594635): Remove all PIP animation code from WM
4015 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4016 */
4017 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004018 stack.animateResizePinnedStack(null /* destBounds */,
4019 null /* sourceHintBounds */, animationDuration,
4020 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004022 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 }
4024 }
4025 } finally {
4026 Binder.restoreCallingIdentity(ident);
4027 }
4028 }
4029
4030 @Override
4031 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 synchronized (mGlobalLock) {
4034 mSuppressResizeConfigChanges = suppress;
4035 }
4036 }
4037
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 @Override
4039 // TODO: API should just be about changing windowing modes...
4040 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004041 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 "moveTasksToFullscreenStack()");
4043 synchronized (mGlobalLock) {
4044 final long origId = Binder.clearCallingIdentity();
4045 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004046 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 if (stack != null){
4048 if (!stack.isActivityTypeStandardOrUndefined()) {
4049 throw new IllegalArgumentException(
4050 "You can't move tasks from non-standard stacks.");
4051 }
4052 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4053 }
4054 } finally {
4055 Binder.restoreCallingIdentity(origId);
4056 }
4057 }
4058 }
4059
4060 /**
4061 * Moves the top activity in the input stackId to the pinned stack.
4062 *
4063 * @param stackId Id of stack to move the top activity to pinned stack.
4064 * @param bounds Bounds to use for pinned stack.
4065 *
4066 * @return True if the top activity of the input stack was successfully moved to the pinned
4067 * stack.
4068 */
4069 @Override
4070 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004071 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004072 "moveTopActivityToPinnedStack()");
4073 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004074 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4076 + "Device doesn't support picture-in-picture mode");
4077 }
4078
4079 long ident = Binder.clearCallingIdentity();
4080 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004081 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 } finally {
4083 Binder.restoreCallingIdentity(ident);
4084 }
4085 }
4086 }
4087
4088 @Override
4089 public boolean isInMultiWindowMode(IBinder token) {
4090 final long origId = Binder.clearCallingIdentity();
4091 try {
4092 synchronized (mGlobalLock) {
4093 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4094 if (r == null) {
4095 return false;
4096 }
4097 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4098 return r.inMultiWindowMode();
4099 }
4100 } finally {
4101 Binder.restoreCallingIdentity(origId);
4102 }
4103 }
4104
4105 @Override
4106 public boolean isInPictureInPictureMode(IBinder token) {
4107 final long origId = Binder.clearCallingIdentity();
4108 try {
4109 synchronized (mGlobalLock) {
4110 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4111 }
4112 } finally {
4113 Binder.restoreCallingIdentity(origId);
4114 }
4115 }
4116
4117 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004118 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4119 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 return false;
4121 }
4122
4123 // If we are animating to fullscreen then we have already dispatched the PIP mode
4124 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004125 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004126 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 }
4128
4129 @Override
4130 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4131 final long origId = Binder.clearCallingIdentity();
4132 try {
4133 synchronized (mGlobalLock) {
4134 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4135 "enterPictureInPictureMode", token, params);
4136
4137 // If the activity is already in picture in picture mode, then just return early
4138 if (isInPictureInPictureMode(r)) {
4139 return true;
4140 }
4141
4142 // Activity supports picture-in-picture, now check that we can enter PiP at this
4143 // point, if it is
4144 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4145 false /* beforeStopping */)) {
4146 return false;
4147 }
4148
4149 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004150 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004151 if (r.getParent() == null) {
4152 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4153 return;
4154 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004155 // Only update the saved args from the args that are set
4156 r.pictureInPictureArgs.copyOnlySet(params);
4157 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4158 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4159 // Adjust the source bounds by the insets for the transition down
4160 final Rect sourceBounds = new Rect(
4161 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004162 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004163 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004164 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004165 stack.setPictureInPictureAspectRatio(aspectRatio);
4166 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004167 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4168 r.info.applicationInfo.uid, r.shortComponentName,
4169 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004170 logPictureInPictureArgs(params);
4171 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 };
4173
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004174 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004175 // If the keyguard is showing or occluded, then try and dismiss it before
4176 // entering picture-in-picture (this will prompt the user to authenticate if the
4177 // device is currently locked).
4178 dismissKeyguard(token, new KeyguardDismissCallback() {
4179 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004180 public void onDismissSucceeded() {
4181 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 }
4183 }, null /* message */);
4184 } else {
4185 // Enter picture in picture immediately otherwise
4186 enterPipRunnable.run();
4187 }
4188 return true;
4189 }
4190 } finally {
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194
4195 @Override
4196 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4197 final long origId = Binder.clearCallingIdentity();
4198 try {
4199 synchronized (mGlobalLock) {
4200 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4201 "setPictureInPictureParams", token, params);
4202
4203 // Only update the saved args from the args that are set
4204 r.pictureInPictureArgs.copyOnlySet(params);
4205 if (r.inPinnedWindowingMode()) {
4206 // If the activity is already in picture-in-picture, update the pinned stack now
4207 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4208 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004209 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 if (!stack.isAnimatingBoundsToFullscreen()) {
4211 stack.setPictureInPictureAspectRatio(
4212 r.pictureInPictureArgs.getAspectRatio());
4213 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4214 }
4215 }
4216 logPictureInPictureArgs(params);
4217 }
4218 } finally {
4219 Binder.restoreCallingIdentity(origId);
4220 }
4221 }
4222
4223 @Override
4224 public int getMaxNumPictureInPictureActions(IBinder token) {
4225 // Currently, this is a static constant, but later, we may change this to be dependent on
4226 // the context of the activity
4227 return 3;
4228 }
4229
4230 private void logPictureInPictureArgs(PictureInPictureParams params) {
4231 if (params.hasSetActions()) {
4232 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4233 params.getActions().size());
4234 }
4235 if (params.hasSetAspectRatio()) {
4236 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4237 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4238 MetricsLogger.action(lm);
4239 }
4240 }
4241
4242 /**
4243 * Checks the state of the system and the activity associated with the given {@param token} to
4244 * verify that picture-in-picture is supported for that activity.
4245 *
4246 * @return the activity record for the given {@param token} if all the checks pass.
4247 */
4248 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4249 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 throw new IllegalStateException(caller
4252 + ": Device doesn't support picture-in-picture mode.");
4253 }
4254
4255 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4256 if (r == null) {
4257 throw new IllegalStateException(caller
4258 + ": Can't find activity for token=" + token);
4259 }
4260
4261 if (!r.supportsPictureInPicture()) {
4262 throw new IllegalStateException(caller
4263 + ": Current activity does not support picture-in-picture.");
4264 }
4265
4266 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004267 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004268 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 final float minAspectRatio = mContext.getResources().getFloat(
4270 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4271 final float maxAspectRatio = mContext.getResources().getFloat(
4272 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4273 throw new IllegalArgumentException(String.format(caller
4274 + ": Aspect ratio is too extreme (must be between %f and %f).",
4275 minAspectRatio, maxAspectRatio));
4276 }
4277
4278 // Truncate the number of actions if necessary
4279 params.truncateActions(getMaxNumPictureInPictureActions(token));
4280
4281 return r;
4282 }
4283
4284 @Override
4285 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004286 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 synchronized (mGlobalLock) {
4288 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4289 if (r == null) {
4290 throw new IllegalArgumentException("Activity does not exist; token="
4291 + activityToken);
4292 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004293 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 }
4295 }
4296
4297 @Override
4298 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4299 Rect tempDockedTaskInsetBounds,
4300 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004301 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 long ident = Binder.clearCallingIdentity();
4303 try {
4304 synchronized (mGlobalLock) {
4305 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4306 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4307 PRESERVE_WINDOWS);
4308 }
4309 } finally {
4310 Binder.restoreCallingIdentity(ident);
4311 }
4312 }
4313
4314 @Override
4315 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 final long ident = Binder.clearCallingIdentity();
4318 try {
4319 synchronized (mGlobalLock) {
4320 mStackSupervisor.setSplitScreenResizing(resizing);
4321 }
4322 } finally {
4323 Binder.restoreCallingIdentity(ident);
4324 }
4325 }
4326
Evan Rosky0037e5f2019-11-05 10:26:24 -08004327 @Override
4328 public ITaskOrganizerController getTaskOrganizerController() {
4329 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4330 "getTaskOrganizerController()");
4331 return mTaskOrganizerController;
4332 }
4333
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004334 /**
4335 * Check that we have the features required for VR-related API calls, and throw an exception if
4336 * not.
4337 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004338 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004339 if (!mContext.getPackageManager().hasSystemFeature(
4340 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4341 throw new UnsupportedOperationException("VR mode not supported on this device!");
4342 }
4343 }
4344
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 @Override
4346 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348
4349 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4350
4351 ActivityRecord r;
4352 synchronized (mGlobalLock) {
4353 r = ActivityRecord.isInStackLocked(token);
4354 }
4355
4356 if (r == null) {
4357 throw new IllegalArgumentException();
4358 }
4359
4360 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004361 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 VrManagerInternal.NO_ERROR) {
4363 return err;
4364 }
4365
4366 // Clear the binder calling uid since this path may call moveToTask().
4367 final long callingId = Binder.clearCallingIdentity();
4368 try {
4369 synchronized (mGlobalLock) {
4370 r.requestedVrComponent = (enabled) ? packageName : null;
4371
4372 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004373 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004374 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 }
4376 return 0;
4377 }
4378 } finally {
4379 Binder.restoreCallingIdentity(callingId);
4380 }
4381 }
4382
4383 @Override
4384 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4385 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4386 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004387 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4389 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4390 }
Louis Changcdec0802019-11-11 11:45:07 +08004391 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 || activity.voiceSession != null) {
4393 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4394 return;
4395 }
4396 if (activity.pendingVoiceInteractionStart) {
4397 Slog.w(TAG, "Pending start of voice interaction already.");
4398 return;
4399 }
4400 activity.pendingVoiceInteractionStart = true;
4401 }
4402 LocalServices.getService(VoiceInteractionManagerInternal.class)
4403 .startLocalVoiceInteraction(callingActivity, options);
4404 }
4405
4406 @Override
4407 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4408 LocalServices.getService(VoiceInteractionManagerInternal.class)
4409 .stopLocalVoiceInteraction(callingActivity);
4410 }
4411
4412 @Override
4413 public boolean supportsLocalVoiceInteraction() {
4414 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4415 .supportsLocalVoiceInteraction();
4416 }
4417
4418 /** Notifies all listeners when the pinned stack animation starts. */
4419 @Override
4420 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 }
4423
4424 /** Notifies all listeners when the pinned stack animation ends. */
4425 @Override
4426 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004427 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 }
4429
4430 @Override
4431 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 final long ident = Binder.clearCallingIdentity();
4434 try {
4435 synchronized (mGlobalLock) {
4436 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4437 }
4438 } finally {
4439 Binder.restoreCallingIdentity(ident);
4440 }
4441 }
4442
4443 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446
4447 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004448 if (mWindowManager == null) {
4449 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4450 return false;
4451 }
4452
4453 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 }
4457
Riddle Hsua0022cd2019-09-09 21:12:41 +08004458 mH.sendMessage(PooledLambda.obtainMessage(
4459 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4460 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461
4462 final long origId = Binder.clearCallingIdentity();
4463 try {
4464 if (values != null) {
4465 Settings.System.clearConfiguration(values);
4466 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 UserHandle.USER_NULL, false /* deferResume */,
4469 mTmpUpdateConfigurationResult);
4470 return mTmpUpdateConfigurationResult.changes != 0;
4471 } finally {
4472 Binder.restoreCallingIdentity(origId);
4473 }
4474 }
4475 }
4476
4477 @Override
4478 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4479 CharSequence message) {
4480 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004481 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4483 }
4484 final long callingId = Binder.clearCallingIdentity();
4485 try {
4486 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004487 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 }
4489 } finally {
4490 Binder.restoreCallingIdentity(callingId);
4491 }
4492 }
4493
4494 @Override
4495 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 "cancelTaskWindowTransition()");
4498 final long ident = Binder.clearCallingIdentity();
4499 try {
4500 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004501 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 MATCH_TASK_IN_STACKS_ONLY);
4503 if (task == null) {
4504 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4505 return;
4506 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004507 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 }
4509 } finally {
4510 Binder.restoreCallingIdentity(ident);
4511 }
4512 }
4513
4514 @Override
4515 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004516 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 final long ident = Binder.clearCallingIdentity();
4518 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004519 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004520 } finally {
4521 Binder.restoreCallingIdentity(ident);
4522 }
4523 }
4524
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004525 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4526 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004527 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004528 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004529 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004530 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4531 if (task == null) {
4532 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4533 return null;
4534 }
4535 }
4536 // Don't call this while holding the lock as this operation might hit the disk.
4537 return task.getSnapshot(reducedResolution, restoreFromDisk);
4538 }
4539
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004540 @Override
4541 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4542 synchronized (mGlobalLock) {
4543 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4544 if (r == null) {
4545 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4546 + token);
4547 return;
4548 }
4549 final long origId = Binder.clearCallingIdentity();
4550 try {
4551 r.setDisablePreviewScreenshots(disable);
4552 } finally {
4553 Binder.restoreCallingIdentity(origId);
4554 }
4555 }
4556 }
4557
Riddle Hsu440f88b2019-11-06 22:17:35 +08004558 @Override
4559 public void invalidateHomeTaskSnapshot(IBinder token) {
4560 synchronized (mGlobalLock) {
4561 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4562 if (r == null || !r.isActivityTypeHome()) {
4563 return;
4564 }
4565 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4566 }
4567 }
4568
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 /** Return the user id of the last resumed activity. */
4570 @Override
4571 public @UserIdInt
4572 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004573 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4575 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004576 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004577 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004579 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 }
4581 }
4582
4583 @Override
4584 public void updateLockTaskFeatures(int userId, int flags) {
4585 final int callingUid = Binder.getCallingUid();
4586 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004587 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004588 "updateLockTaskFeatures()");
4589 }
4590 synchronized (mGlobalLock) {
4591 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4592 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004593 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 }
4595 }
4596
4597 @Override
4598 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4599 synchronized (mGlobalLock) {
4600 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4601 if (r == null) {
4602 return;
4603 }
4604 final long origId = Binder.clearCallingIdentity();
4605 try {
4606 r.setShowWhenLocked(showWhenLocked);
4607 } finally {
4608 Binder.restoreCallingIdentity(origId);
4609 }
4610 }
4611 }
4612
4613 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004614 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4615 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.setInheritShowWhenLocked(inheritShowWhenLocked);
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627 }
4628
4629 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4631 synchronized (mGlobalLock) {
4632 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4633 if (r == null) {
4634 return;
4635 }
4636 final long origId = Binder.clearCallingIdentity();
4637 try {
4638 r.setTurnScreenOn(turnScreenOn);
4639 } finally {
4640 Binder.restoreCallingIdentity(origId);
4641 }
4642 }
4643 }
4644
4645 @Override
4646 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004647 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004649 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004650 synchronized (mGlobalLock) {
4651 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4652 if (r == null) {
4653 return;
4654 }
4655 final long origId = Binder.clearCallingIdentity();
4656 try {
4657 r.registerRemoteAnimations(definition);
4658 } finally {
4659 Binder.restoreCallingIdentity(origId);
4660 }
4661 }
4662 }
4663
4664 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004665 public void unregisterRemoteAnimations(IBinder token) {
4666 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4667 "unregisterRemoteAnimations");
4668 synchronized (mGlobalLock) {
4669 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4670 if (r == null) {
4671 return;
4672 }
4673 final long origId = Binder.clearCallingIdentity();
4674 try {
4675 r.unregisterRemoteAnimations();
4676 } finally {
4677 Binder.restoreCallingIdentity(origId);
4678 }
4679 }
4680 }
4681
4682 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004683 public void registerRemoteAnimationForNextActivityStart(String packageName,
4684 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004685 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004686 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004687 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 synchronized (mGlobalLock) {
4689 final long origId = Binder.clearCallingIdentity();
4690 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004691 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004692 packageName, adapter);
4693 } finally {
4694 Binder.restoreCallingIdentity(origId);
4695 }
4696 }
4697 }
4698
Evan Rosky966759f2019-01-15 10:33:58 -08004699 @Override
4700 public void registerRemoteAnimationsForDisplay(int displayId,
4701 RemoteAnimationDefinition definition) {
4702 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4703 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004704 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004705 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004706 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004707 if (display == null) {
4708 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4709 return;
4710 }
4711 final long origId = Binder.clearCallingIdentity();
4712 try {
4713 display.mDisplayContent.registerRemoteAnimations(definition);
4714 } finally {
4715 Binder.restoreCallingIdentity(origId);
4716 }
4717 }
4718 }
4719
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004720 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4721 @Override
4722 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4723 synchronized (mGlobalLock) {
4724 final long origId = Binder.clearCallingIdentity();
4725 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004726 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004727 } finally {
4728 Binder.restoreCallingIdentity(origId);
4729 }
4730 }
4731 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004732
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004733 @Override
4734 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004735 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004736 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004737 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004738 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004739 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004740 }
4741 }
4742
4743 @Override
4744 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004746 != PERMISSION_GRANTED) {
4747 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4748 + Binder.getCallingPid()
4749 + ", uid=" + Binder.getCallingUid()
4750 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4751 Slog.w(TAG, msg);
4752 throw new SecurityException(msg);
4753 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004754 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004755 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004756 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004757 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004758 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004759 }
4760 }
4761
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004762 @Override
4763 public void stopAppSwitches() {
4764 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4765 synchronized (mGlobalLock) {
4766 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004767 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004768 mDidAppSwitch = false;
4769 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4770 }
4771 }
4772
4773 @Override
4774 public void resumeAppSwitches() {
4775 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4776 synchronized (mGlobalLock) {
4777 // Note that we don't execute any pending app switches... we will
4778 // let those wait until either the timeout, or the next start
4779 // activity request.
4780 mAppSwitchesAllowedTime = 0;
4781 }
4782 }
4783
Ricky Wai906af482019-06-03 17:25:28 +01004784 long getLastStopAppSwitchesTime() {
4785 return mLastStopAppSwitchesTime;
4786 }
4787
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004788 void onStartActivitySetDidAppSwitch() {
4789 if (mDidAppSwitch) {
4790 // This is the second allowed switch since we stopped switches, so now just generally
4791 // allow switches. Use case:
4792 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4793 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4794 // anyone to switch again).
4795 mAppSwitchesAllowedTime = 0;
4796 } else {
4797 mDidAppSwitch = true;
4798 }
4799 }
4800
4801 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004802 boolean shouldDisableNonVrUiLocked() {
4803 return mVrController.shouldDisableNonVrUiLocked();
4804 }
4805
Wale Ogunwale53783742018-09-16 10:21:51 -07004806 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004807 // 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 +00004808 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004810 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4811 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004812 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004813 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004814 }
4815 mH.post(() -> {
4816 if (!mVrController.onVrModeChanged(r)) {
4817 return;
4818 }
4819 synchronized (mGlobalLock) {
4820 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4821 mWindowManager.disableNonVrUi(disableNonVrUi);
4822 if (disableNonVrUi) {
4823 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4824 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004825 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004826 }
4827 }
4828 });
4829 }
4830
Wale Ogunwale53783742018-09-16 10:21:51 -07004831 @Override
4832 public int getPackageScreenCompatMode(String packageName) {
4833 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4834 synchronized (mGlobalLock) {
4835 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4836 }
4837 }
4838
4839 @Override
4840 public void setPackageScreenCompatMode(String packageName, int mode) {
4841 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4842 "setPackageScreenCompatMode");
4843 synchronized (mGlobalLock) {
4844 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4845 }
4846 }
4847
4848 @Override
4849 public boolean getPackageAskScreenCompat(String packageName) {
4850 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4851 synchronized (mGlobalLock) {
4852 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4853 }
4854 }
4855
4856 @Override
4857 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4858 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4859 "setPackageAskScreenCompat");
4860 synchronized (mGlobalLock) {
4861 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4862 }
4863 }
4864
Wale Ogunwale64258362018-10-16 15:13:37 -07004865 public static String relaunchReasonToString(int relaunchReason) {
4866 switch (relaunchReason) {
4867 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4868 return "window_resize";
4869 case RELAUNCH_REASON_FREE_RESIZE:
4870 return "free_resize";
4871 default:
4872 return null;
4873 }
4874 }
4875
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004876 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004877 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004878 }
4879
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004880 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004881 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004882 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4883 }
4884
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004885 boolean isKeyguardLocked() {
4886 return mKeyguardController.isKeyguardLocked();
4887 }
4888
Garfield Tan01548632018-11-27 10:15:48 -08004889 /**
4890 * Clears launch params for the given package.
4891 * @param packageNames the names of the packages of which the launch params are to be cleared
4892 */
4893 @Override
4894 public void clearLaunchParamsForPackages(List<String> packageNames) {
4895 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4896 "clearLaunchParamsForPackages");
4897 synchronized (mGlobalLock) {
4898 for (int i = 0; i < packageNames.size(); ++i) {
4899 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4900 }
4901 }
4902 }
4903
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004904 /**
4905 * Makes the display with the given id a single task instance display. I.e the display can only
4906 * contain one task.
4907 */
4908 @Override
4909 public void setDisplayToSingleTaskInstance(int displayId) {
4910 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4911 "setDisplayToSingleTaskInstance");
4912 final long origId = Binder.clearCallingIdentity();
4913 try {
Louis Chang677921f2019-12-06 16:44:24 +08004914 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004915 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004916 if (display != null) {
4917 display.setDisplayToSingleTaskInstance();
4918 }
4919 } finally {
4920 Binder.restoreCallingIdentity(origId);
4921 }
4922 }
4923
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004924 /**
4925 * Requests that an activity should enter picture-in-picture mode if possible.
4926 */
4927 @Override
4928 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4929 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4930 "requestPictureInPictureMode");
4931 final long origId = Binder.clearCallingIdentity();
4932 try {
4933 synchronized (mGlobalLock) {
4934 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4935 if (activity == null) {
4936 return;
4937 }
4938
4939 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4940 "requestPictureInPictureMode", /* beforeStopping */ false);
4941 if (!canEnterPictureInPicture) {
4942 throw new IllegalStateException(
4943 "Requested PIP on an activity that doesn't support it");
4944 }
4945
4946 try {
4947 final ClientTransaction transaction = ClientTransaction.obtain(
4948 activity.app.getThread(),
4949 activity.token);
4950 transaction.addCallback(EnterPipRequestedItem.obtain());
4951 getLifecycleManager().scheduleTransaction(transaction);
4952 } catch (Exception e) {
4953 Slog.w(TAG, "Failed to send enter pip requested item: "
4954 + activity.intent.getComponent(), e);
4955 }
4956 }
4957 } finally {
4958 Binder.restoreCallingIdentity(origId);
4959 }
4960 }
4961
Wale Ogunwale31913b52018-10-13 08:29:31 -07004962 void dumpLastANRLocked(PrintWriter pw) {
4963 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4964 if (mLastANRState == null) {
4965 pw.println(" <no ANR has occurred since boot>");
4966 } else {
4967 pw.println(mLastANRState);
4968 }
4969 }
4970
4971 void dumpLastANRTracesLocked(PrintWriter pw) {
4972 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4973
4974 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4975 if (ArrayUtils.isEmpty(files)) {
4976 pw.println(" <no ANR has occurred since boot>");
4977 return;
4978 }
4979 // Find the latest file.
4980 File latest = null;
4981 for (File f : files) {
4982 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4983 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004984 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004985 }
4986 pw.print("File: ");
4987 pw.print(latest.getName());
4988 pw.println();
4989 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4990 String line;
4991 while ((line = in.readLine()) != null) {
4992 pw.println(line);
4993 }
4994 } catch (IOException e) {
4995 pw.print("Unable to read: ");
4996 pw.print(e);
4997 pw.println();
4998 }
4999 }
5000
5001 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5002 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5003 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5004 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5005 }
5006
5007 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5008 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5009 pw.println(header);
5010
Louis Chang149d5c82019-12-30 09:47:39 +08005011 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005012 dumpPackage);
5013 boolean needSep = printedAnything;
5014
5015 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005016 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005017 " ResumedActivity: ");
5018 if (printed) {
5019 printedAnything = true;
5020 needSep = false;
5021 }
5022
5023 if (dumpPackage == null) {
5024 if (needSep) {
5025 pw.println();
5026 }
5027 printedAnything = true;
5028 mStackSupervisor.dump(pw, " ");
5029 }
5030
5031 if (!printedAnything) {
5032 pw.println(" (nothing)");
5033 }
5034 }
5035
5036 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005037 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005038 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005039 pw.println(" ");
5040 }
5041
5042 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5043 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5044 getActivityStartController().dump(pw, "", dumpPackage);
5045 }
5046
5047 /**
5048 * There are three things that cmd can be:
5049 * - a flattened component name that matches an existing activity
5050 * - the cmd arg isn't the flattened component name of an existing activity:
5051 * dump all activity whose component contains the cmd as a substring
5052 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005053 * <p>
5054 * The caller should not hold lock when calling this method because it will wait for the
5055 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 *
5057 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5058 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5059 */
5060 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5061 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5062 ArrayList<ActivityRecord> activities;
5063
5064 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005065 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005066 dumpFocusedStackOnly);
5067 }
5068
5069 if (activities.size() <= 0) {
5070 return false;
5071 }
5072
5073 String[] newArgs = new String[args.length - opti];
5074 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5075
Louis Changcdec0802019-11-11 11:45:07 +08005076 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005077 boolean needSep = false;
5078 for (int i = activities.size() - 1; i >= 0; i--) {
5079 ActivityRecord r = activities.get(i);
5080 if (needSep) {
5081 pw.println();
5082 }
5083 needSep = true;
5084 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005085 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005086 if (lastTask != task) {
5087 lastTask = task;
5088 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005089 pw.print(" id="); pw.print(lastTask.mTaskId);
5090 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005091 if (dumpAll) {
5092 lastTask.dump(pw, " ");
5093 }
5094 }
5095 }
5096 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5097 }
5098 return true;
5099 }
5100
5101 /**
5102 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5103 * there is a thread associated with the activity.
5104 */
5105 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5106 final ActivityRecord r, String[] args, boolean dumpAll) {
5107 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005108 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005109 synchronized (mGlobalLock) {
5110 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5111 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5112 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005113 if (r.hasProcess()) {
5114 pw.println(r.app.getPid());
5115 appThread = r.app.getThread();
5116 } else {
5117 pw.println("(not running)");
5118 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005119 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005120 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005121 }
5122 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005123 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005124 // flush anything that is already in the PrintWriter since the thread is going
5125 // to write to the file descriptor directly
5126 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005127 try (TransferPipe tp = new TransferPipe()) {
5128 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5129 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005130 } catch (IOException e) {
5131 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5132 } catch (RemoteException e) {
5133 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5134 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005135 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005136 }
5137
sanryhuang498e77e2018-12-06 14:57:01 +08005138 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5139 boolean testPssMode) {
5140 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5141 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5142 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005143 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005144 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5145 st.toString());
5146 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5148 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5149 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005150 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5151 testPssMode);
5152 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005153 }
5154
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005155 int getCurrentUserId() {
5156 return mAmInternal.getCurrentUserId();
5157 }
5158
5159 private void enforceNotIsolatedCaller(String caller) {
5160 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5161 throw new SecurityException("Isolated process not allowed to call " + caller);
5162 }
5163 }
5164
Wale Ogunwalef6733932018-06-27 05:14:34 -07005165 public Configuration getConfiguration() {
5166 Configuration ci;
5167 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005168 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005169 ci.userSetLocale = false;
5170 }
5171 return ci;
5172 }
5173
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005174 /**
5175 * Current global configuration information. Contains general settings for the entire system,
5176 * also corresponds to the merged configuration of the default display.
5177 */
5178 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005179 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005180 // while initializing process record for system, see {@link
5181 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005182 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005183 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184 }
5185
5186 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5187 boolean initLocale) {
5188 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5189 }
5190
5191 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5192 boolean initLocale, boolean deferResume) {
5193 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5194 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5195 UserHandle.USER_NULL, deferResume);
5196 }
5197
Wale Ogunwale59507092018-10-29 09:00:30 -07005198 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005199 final long origId = Binder.clearCallingIdentity();
5200 try {
5201 synchronized (mGlobalLock) {
5202 updateConfigurationLocked(values, null, false, true, userId,
5203 false /* deferResume */);
5204 }
5205 } finally {
5206 Binder.restoreCallingIdentity(origId);
5207 }
5208 }
5209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5211 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5212 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5213 deferResume, null /* result */);
5214 }
5215
5216 /**
5217 * Do either or both things: (1) change the current configuration, and (2)
5218 * make sure the given activity is running with the (now) current
5219 * configuration. Returns true if the activity has been left running, or
5220 * false if <var>starting</var> is being destroyed to match the new
5221 * configuration.
5222 *
5223 * @param userId is only used when persistent parameter is set to true to persist configuration
5224 * for that particular user
5225 */
5226 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5227 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5228 ActivityTaskManagerService.UpdateConfigurationResult result) {
5229 int changes = 0;
5230 boolean kept = true;
5231
Riddle Hsua0022cd2019-09-09 21:12:41 +08005232 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233 try {
5234 if (values != null) {
5235 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5236 deferResume);
5237 }
5238
5239 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5240 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005241 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242 }
5243
5244 if (result != null) {
5245 result.changes = changes;
5246 result.activityRelaunched = !kept;
5247 }
5248 return kept;
5249 }
5250
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005252 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005253 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005254
Louis Chang677921f2019-12-06 16:44:24 +08005255 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005256 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005257
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005258 mTempConfig.setTo(getGlobalConfiguration());
5259 final int changes = mTempConfig.updateFrom(values);
5260 if (changes == 0) {
5261 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5262 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5263 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5264 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005265 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 return 0;
5267 }
5268
5269 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5270 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005271 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005272 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273 values.colorMode,
5274 values.densityDpi,
5275 values.fontScale,
5276 values.hardKeyboardHidden,
5277 values.keyboard,
5278 values.keyboardHidden,
5279 values.mcc,
5280 values.mnc,
5281 values.navigation,
5282 values.navigationHidden,
5283 values.orientation,
5284 values.screenHeightDp,
5285 values.screenLayout,
5286 values.screenWidthDp,
5287 values.smallestScreenWidthDp,
5288 values.touchscreen,
5289 values.uiMode);
5290
5291
5292 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5293 final LocaleList locales = values.getLocales();
5294 int bestLocaleIndex = 0;
5295 if (locales.size() > 1) {
5296 if (mSupportedSystemLocales == null) {
5297 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5298 }
5299 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5300 }
5301 SystemProperties.set("persist.sys.locale",
5302 locales.get(bestLocaleIndex).toLanguageTag());
5303 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005304
5305 final Message m = PooledLambda.obtainMessage(
5306 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5307 locales.get(bestLocaleIndex));
5308 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309 }
5310
Yunfan Chen75157d72018-07-27 14:47:21 +09005311 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005312
5313 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005314 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005315
5316 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5317 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005318 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005319
5320 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005321 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005322
5323 AttributeCache ac = AttributeCache.instance();
5324 if (ac != null) {
5325 ac.updateConfiguration(mTempConfig);
5326 }
5327
5328 // Make sure all resources in our process are updated right now, so that anyone who is going
5329 // to retrieve resource values after we return will be sure to get the new ones. This is
5330 // especially important during boot, where the first config change needs to guarantee all
5331 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005332 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333
5334 // We need another copy of global config because we're scheduling some calls instead of
5335 // running them in place. We need to be sure that object we send will be handled unchanged.
5336 final Configuration configCopy = new Configuration(mTempConfig);
5337 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005338 final Message msg = PooledLambda.obtainMessage(
5339 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5340 this, userId, configCopy);
5341 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342 }
5343
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005344 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5345 for (int i = pidMap.size() - 1; i >= 0; i--) {
5346 final int pid = pidMap.keyAt(i);
5347 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005348 if (DEBUG_CONFIGURATION) {
5349 Slog.v(TAG_CONFIGURATION, "Update process config of "
5350 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005352 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353 }
5354
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005355 final Message msg = PooledLambda.obtainMessage(
5356 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5357 mAmInternal, changes, initLocale);
5358 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005359
5360 // Override configuration of the default display duplicates global config, so we need to
5361 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005362 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005363 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005364
5365 return changes;
5366 }
5367
Riddle Hsua0022cd2019-09-09 21:12:41 +08005368 /** @see WindowSurfacePlacer#deferLayout */
5369 void deferWindowLayout() {
5370 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5371 // Reset the reasons at the first entrance because we only care about the changes in the
5372 // deferred scope.
5373 mLayoutReasons = 0;
5374 }
5375
5376 mWindowManager.mWindowPlacerLocked.deferLayout();
5377 }
5378
5379 /** @see WindowSurfacePlacer#continueLayout */
5380 void continueWindowLayout() {
5381 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5382 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5383 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5384 }
5385 }
5386
5387 /**
5388 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5389 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5390 * defer count is gone.
5391 */
5392 void addWindowLayoutReasons(@LayoutReason int reasons) {
5393 mLayoutReasons |= reasons;
5394 }
5395
Wale Ogunwalef6733932018-06-27 05:14:34 -07005396 private void updateEventDispatchingLocked(boolean booted) {
5397 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5398 }
5399
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005400 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5401 final ContentResolver resolver = mContext.getContentResolver();
5402 Settings.System.putConfigurationForUser(resolver, config, userId);
5403 }
5404
5405 private void sendLocaleToMountDaemonMsg(Locale l) {
5406 try {
5407 IBinder service = ServiceManager.getService("mount");
5408 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5409 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5410 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5411 } catch (RemoteException e) {
5412 Log.e(TAG, "Error storing locale for decryption UI", e);
5413 }
5414 }
5415
Alison Cichowlas3e340502018-08-07 17:15:01 -04005416 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5417 mStartActivitySources.remove(permissionToken);
5418 mExpiredStartAsCallerTokens.add(permissionToken);
5419 }
5420
5421 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5422 mExpiredStartAsCallerTokens.remove(permissionToken);
5423 }
5424
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005425 boolean isActivityStartsLoggingEnabled() {
5426 return mAmInternal.isActivityStartsLoggingEnabled();
5427 }
5428
Michal Karpinski8596ded2018-11-14 14:43:48 +00005429 boolean isBackgroundActivityStartsEnabled() {
5430 return mAmInternal.isBackgroundActivityStartsEnabled();
5431 }
5432
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005434 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 mWindowManager.enableScreenAfterBoot();
5436
5437 synchronized (mGlobalLock) {
5438 updateEventDispatchingLocked(booted);
5439 }
5440 }
5441
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005442 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5443 if (r == null || !r.hasProcess()) {
5444 return KEY_DISPATCHING_TIMEOUT_MS;
5445 }
5446 return getInputDispatchingTimeoutLocked(r.app);
5447 }
5448
5449 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005450 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005451 }
5452
Wale Ogunwalef6733932018-06-27 05:14:34 -07005453 /**
5454 * Decide based on the configuration whether we should show the ANR,
5455 * crash, etc dialogs. The idea is that if there is no affordance to
5456 * press the on-screen buttons, or the user experience would be more
5457 * greatly impacted than the crash itself, we shouldn't show the dialog.
5458 *
5459 * A thought: SystemUI might also want to get told about this, the Power
5460 * dialog / global actions also might want different behaviors.
5461 */
5462 private void updateShouldShowDialogsLocked(Configuration config) {
5463 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5464 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5465 && config.navigation == Configuration.NAVIGATION_NONAV);
5466 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5467 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5468 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5469 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5470 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5471 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5472 HIDE_ERROR_DIALOGS, 0) != 0;
5473 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5474 }
5475
5476 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5477 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5478 FONT_SCALE, 1.0f, userId);
5479
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005480 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005481 if (getGlobalConfiguration().fontScale == scaleFactor) {
5482 return;
5483 }
5484
5485 final Configuration configuration
5486 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5487 configuration.fontScale = scaleFactor;
5488 updatePersistentConfiguration(configuration, userId);
5489 }
5490 }
5491
5492 // Actually is sleeping or shutting down or whatever else in the future
5493 // is an inactive state.
5494 boolean isSleepingOrShuttingDownLocked() {
5495 return isSleepingLocked() || mShuttingDown;
5496 }
5497
5498 boolean isSleepingLocked() {
5499 return mSleeping;
5500 }
5501
Riddle Hsu16567132018-08-16 21:37:47 +08005502 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005504 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005505 if (task.isActivityTypeStandard()) {
5506 if (mCurAppTimeTracker != r.appTimeTracker) {
5507 // We are switching app tracking. Complete the current one.
5508 if (mCurAppTimeTracker != null) {
5509 mCurAppTimeTracker.stop();
5510 mH.obtainMessage(
5511 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005512 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513 mCurAppTimeTracker = null;
5514 }
5515 if (r.appTimeTracker != null) {
5516 mCurAppTimeTracker = r.appTimeTracker;
5517 startTimeTrackingFocusedActivityLocked();
5518 }
5519 } else {
5520 startTimeTrackingFocusedActivityLocked();
5521 }
5522 } else {
5523 r.appTimeTracker = null;
5524 }
5525 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5526 // TODO: Probably not, because we don't want to resume voice on switching
5527 // back to this activity
5528 if (task.voiceInteractor != null) {
5529 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5530 } else {
5531 finishRunningVoiceLocked();
5532
5533 if (mLastResumedActivity != null) {
5534 final IVoiceInteractionSession session;
5535
Louis Changcdec0802019-11-11 11:45:07 +08005536 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005537 if (lastResumedActivityTask != null
5538 && lastResumedActivityTask.voiceSession != null) {
5539 session = lastResumedActivityTask.voiceSession;
5540 } else {
5541 session = mLastResumedActivity.voiceSession;
5542 }
5543
5544 if (session != null) {
5545 // We had been in a voice interaction session, but now focused has
5546 // move to something different. Just finish the session, we can't
5547 // return to it and retain the proper state and synchronization with
5548 // the voice interaction service.
5549 finishVoiceTask(session);
5550 }
5551 }
5552 }
5553
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005554 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5555 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005556 }
5557 updateResumedAppTrace(r);
5558 mLastResumedActivity = r;
5559
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005560 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005561
5562 applyUpdateLockStateLocked(r);
5563 applyUpdateVrModeLocked(r);
5564
Jeff Changd136e772019-11-05 20:33:52 +08005565 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005566 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005567 r == null ? "NULL" : r.shortComponentName,
5568 reason);
5569 }
5570
5571 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5572 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005573 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005574 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005575 updateSleepIfNeededLocked();
5576 return token;
5577 }
5578 }
5579
5580 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005581 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 final boolean wasSleeping = mSleeping;
5583 boolean updateOomAdj = false;
5584
5585 if (!shouldSleep) {
5586 // If wasSleeping is true, we need to wake up activity manager state from when
5587 // we started sleeping. In either case, we need to apply the sleep tokens, which
5588 // will wake up stacks or put them to sleep as appropriate.
5589 if (wasSleeping) {
5590 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005591 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5592 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005593 startTimeTrackingFocusedActivityLocked();
5594 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005595 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005596 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5597 }
Louis Chang149d5c82019-12-30 09:47:39 +08005598 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005599 if (wasSleeping) {
5600 updateOomAdj = true;
5601 }
5602 } else if (!mSleeping && shouldSleep) {
5603 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005604 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5605 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 if (mCurAppTimeTracker != null) {
5607 mCurAppTimeTracker.stop();
5608 }
5609 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005610 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005611 mStackSupervisor.goingToSleepLocked();
5612 updateResumedAppTrace(null /* resumed */);
5613 updateOomAdj = true;
5614 }
5615 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005616 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005617 }
5618 }
5619
5620 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005621 mH.removeCallbacks(mUpdateOomAdjRunnable);
5622 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005623 }
5624
Wale Ogunwale53783742018-09-16 10:21:51 -07005625 void updateCpuStats() {
5626 mH.post(mAmInternal::updateCpuStats);
5627 }
5628
Hui Yu03d12402018-12-06 18:00:37 -08005629 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5630 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005631 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5632 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005633 mH.sendMessage(m);
5634 }
5635
Hui Yu03d12402018-12-06 18:00:37 -08005636 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005637 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005638 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005639 if (task != null) {
5640 final ActivityRecord rootActivity = task.getRootActivity();
5641 if (rootActivity != null) {
5642 taskRoot = rootActivity.mActivityComponent;
5643 }
5644 }
5645
Hui Yu03d12402018-12-06 18:00:37 -08005646 final Message m = PooledLambda.obtainMessage(
5647 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005648 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005649 mH.sendMessage(m);
5650 }
5651
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005652 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5653 String hostingType) {
5654 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005655 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5656 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005657 + activity.processName);
5658 }
5659 // Post message to start process to avoid possible deadlock of calling into AMS with the
5660 // ATMS lock held.
5661 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5662 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5663 isTop, hostingType, activity.intent.getComponent());
5664 mH.sendMessage(m);
5665 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005666 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005667 }
5668 }
5669
Wale Ogunwale53783742018-09-16 10:21:51 -07005670 void setBooting(boolean booting) {
5671 mAmInternal.setBooting(booting);
5672 }
5673
5674 boolean isBooting() {
5675 return mAmInternal.isBooting();
5676 }
5677
5678 void setBooted(boolean booted) {
5679 mAmInternal.setBooted(booted);
5680 }
5681
5682 boolean isBooted() {
5683 return mAmInternal.isBooted();
5684 }
5685
5686 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5687 mH.post(() -> {
5688 if (finishBooting) {
5689 mAmInternal.finishBooting();
5690 }
5691 if (enableScreen) {
5692 mInternal.enableScreenAfterBoot(isBooted());
5693 }
5694 });
5695 }
5696
5697 void setHeavyWeightProcess(ActivityRecord root) {
5698 mHeavyWeightProcess = root.app;
5699 final Message m = PooledLambda.obtainMessage(
5700 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005701 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005702 mH.sendMessage(m);
5703 }
5704
5705 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5706 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5707 return;
5708 }
5709
5710 mHeavyWeightProcess = null;
5711 final Message m = PooledLambda.obtainMessage(
5712 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5713 proc.mUserId);
5714 mH.sendMessage(m);
5715 }
5716
5717 private void cancelHeavyWeightProcessNotification(int userId) {
5718 final INotificationManager inm = NotificationManager.getService();
5719 if (inm == null) {
5720 return;
5721 }
5722 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005723 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005724 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5725 } catch (RuntimeException e) {
5726 Slog.w(TAG, "Error canceling notification for service", e);
5727 } catch (RemoteException e) {
5728 }
5729
5730 }
5731
5732 private void postHeavyWeightProcessNotification(
5733 WindowProcessController proc, Intent intent, int userId) {
5734 if (proc == null) {
5735 return;
5736 }
5737
5738 final INotificationManager inm = NotificationManager.getService();
5739 if (inm == null) {
5740 return;
5741 }
5742
5743 try {
5744 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5745 String text = mContext.getString(R.string.heavy_weight_notification,
5746 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5747 Notification notification =
5748 new Notification.Builder(context,
5749 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5750 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5751 .setWhen(0)
5752 .setOngoing(true)
5753 .setTicker(text)
5754 .setColor(mContext.getColor(
5755 com.android.internal.R.color.system_notification_accent_color))
5756 .setContentTitle(text)
5757 .setContentText(
5758 mContext.getText(R.string.heavy_weight_notification_detail))
5759 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5760 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5761 new UserHandle(userId)))
5762 .build();
5763 try {
5764 inm.enqueueNotificationWithTag("android", "android", null,
5765 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5766 } catch (RuntimeException e) {
5767 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5768 } catch (RemoteException e) {
5769 }
5770 } catch (PackageManager.NameNotFoundException e) {
5771 Slog.w(TAG, "Unable to create context for heavy notification", e);
5772 }
5773
5774 }
5775
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005776 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5777 IBinder token, String resultWho, int requestCode, Intent[] intents,
5778 String[] resolvedTypes, int flags, Bundle bOptions) {
5779
5780 ActivityRecord activity = null;
5781 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5782 activity = ActivityRecord.isInStackLocked(token);
5783 if (activity == null) {
5784 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5785 return null;
5786 }
5787 if (activity.finishing) {
5788 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5789 return null;
5790 }
5791 }
5792
5793 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5794 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5795 bOptions);
5796 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5797 if (noCreate) {
5798 return rec;
5799 }
5800 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5801 if (activity.pendingResults == null) {
5802 activity.pendingResults = new HashSet<>();
5803 }
5804 activity.pendingResults.add(rec.ref);
5805 }
5806 return rec;
5807 }
5808
Andrii Kulian52d255c2018-07-13 11:32:19 -07005809 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005810 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005811 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005812 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5813 mCurAppTimeTracker.start(resumedActivity.packageName);
5814 }
5815 }
5816
5817 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5818 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005819 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005820 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5821 }
5822 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005823 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005824 constructResumedTraceName(resumed.packageName), 0);
5825 }
5826 mTracedResumedActivity = resumed;
5827 }
5828
5829 private String constructResumedTraceName(String packageName) {
5830 return "focused app: " + packageName;
5831 }
5832
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005833 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005834 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005835 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005836 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837 // mainStack is null during startup.
5838 if (mainStack != null) {
5839 if (changes != 0 && starting == null) {
5840 // If the configuration changed, and the caller is not already
5841 // in the process of starting an activity, then find the top
5842 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005843 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 }
5845
5846 if (starting != null) {
5847 kept = starting.ensureActivityConfiguration(changes,
5848 false /* preserveWindow */);
5849 // And we need to make sure at this point that all other activities
5850 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005851 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005852 !PRESERVE_WINDOWS);
5853 }
5854 }
5855
5856 return kept;
5857 }
5858
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005859 void scheduleAppGcsLocked() {
5860 mH.post(() -> mAmInternal.scheduleAppGcs());
5861 }
5862
Wale Ogunwale53783742018-09-16 10:21:51 -07005863 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5864 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5865 }
5866
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005867 /**
5868 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5869 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5870 * on demand.
5871 */
5872 IPackageManager getPackageManager() {
5873 return AppGlobals.getPackageManager();
5874 }
5875
5876 PackageManagerInternal getPackageManagerInternalLocked() {
5877 if (mPmInternal == null) {
5878 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5879 }
5880 return mPmInternal;
5881 }
5882
Hai Zhangf4da9be2019-05-01 13:46:06 +08005883 PermissionPolicyInternal getPermissionPolicyInternal() {
5884 if (mPermissionPolicyInternal == null) {
5885 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5886 }
5887 return mPermissionPolicyInternal;
5888 }
5889
Wale Ogunwale008163e2018-07-23 23:11:08 -07005890 AppWarnings getAppWarningsLocked() {
5891 return mAppWarnings;
5892 }
5893
Wale Ogunwale214f3482018-10-04 11:00:47 -07005894 Intent getHomeIntent() {
5895 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5896 intent.setComponent(mTopComponent);
5897 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5898 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5899 intent.addCategory(Intent.CATEGORY_HOME);
5900 }
5901 return intent;
5902 }
5903
Chilun2ef71f72018-11-16 17:57:15 +08005904 /**
5905 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5906 * activities.
5907 *
5908 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5909 * component defined in config_secondaryHomeComponent.
5910 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5911 */
5912 Intent getSecondaryHomeIntent(String preferredPackage) {
5913 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005914 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5915 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5916 if (preferredPackage == null || useSystemProvidedLauncher) {
5917 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005918 final String secondaryHomeComponent = mContext.getResources().getString(
5919 com.android.internal.R.string.config_secondaryHomeComponent);
5920 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5921 } else {
5922 intent.setPackage(preferredPackage);
5923 }
5924 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5925 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5926 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5927 }
5928 return intent;
5929 }
5930
Wale Ogunwale214f3482018-10-04 11:00:47 -07005931 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5932 if (info == null) return null;
5933 ApplicationInfo newInfo = new ApplicationInfo(info);
5934 newInfo.initForUser(userId);
5935 return newInfo;
5936 }
5937
Wale Ogunwale9c103022018-10-18 07:44:54 -07005938 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005939 if (uid == SYSTEM_UID) {
5940 // The system gets to run in any process. If there are multiple processes with the same
5941 // uid, just pick the first (this should never happen).
5942 final SparseArray<WindowProcessController> procs =
5943 mProcessNames.getMap().get(processName);
5944 if (procs == null) return null;
5945 final int procCount = procs.size();
5946 for (int i = 0; i < procCount; i++) {
5947 final int procUid = procs.keyAt(i);
5948 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5949 // Don't use an app process or different user process for system component.
5950 continue;
5951 }
5952 return procs.valueAt(i);
5953 }
5954 }
5955
5956 return mProcessNames.get(processName, uid);
5957 }
5958
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005959 WindowProcessController getProcessController(IApplicationThread thread) {
5960 if (thread == null) {
5961 return null;
5962 }
5963
5964 final IBinder threadBinder = thread.asBinder();
5965 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5966 for (int i = pmap.size()-1; i >= 0; i--) {
5967 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5968 for (int j = procs.size() - 1; j >= 0; j--) {
5969 final WindowProcessController proc = procs.valueAt(j);
5970 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5971 return proc;
5972 }
5973 }
5974 }
5975
5976 return null;
5977 }
5978
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005979 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005980 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005981 if (proc == null) return null;
5982 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5983 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005984 }
5985 return null;
5986 }
5987
Riddle Hsua0536432019-02-16 00:38:59 +08005988 int getUidState(int uid) {
5989 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005990 }
5991
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005992 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005993 // A uid is considered to be foreground if it has a visible non-toast window.
5994 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005995 }
5996
Ricky Wai96f5c352019-04-10 18:40:17 +01005997 boolean isDeviceOwner(int uid) {
5998 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005999 }
6000
Ricky Wai96f5c352019-04-10 18:40:17 +01006001 void setDeviceOwnerUid(int uid) {
6002 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006003 }
6004
Wale Ogunwale9de19442018-10-18 19:05:03 -07006005 /**
6006 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6007 * the whitelist
6008 */
6009 String getPendingTempWhitelistTagForUidLocked(int uid) {
6010 return mPendingTempWhitelist.get(uid);
6011 }
6012
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006013 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6014 if (true || Build.IS_USER) {
6015 return;
6016 }
6017
6018 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6019 StrictMode.allowThreadDiskWrites();
6020 try {
6021 File tracesDir = new File("/data/anr");
6022 File tracesFile = null;
6023 try {
6024 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6025
6026 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006027 String timeString =
6028 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6029 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006030 sb.append(": ");
6031 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6032 sb.append(" since ");
6033 sb.append(msg);
6034 FileOutputStream fos = new FileOutputStream(tracesFile);
6035 fos.write(sb.toString().getBytes());
6036 if (app == null) {
6037 fos.write("\n*** No application process!".getBytes());
6038 }
6039 fos.close();
6040 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6041 } catch (IOException e) {
6042 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6043 return;
6044 }
6045
6046 if (app != null && app.getPid() > 0) {
6047 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6048 firstPids.add(app.getPid());
6049 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6050 }
6051
6052 File lastTracesFile = null;
6053 File curTracesFile = null;
6054 for (int i=9; i>=0; i--) {
6055 String name = String.format(Locale.US, "slow%02d.txt", i);
6056 curTracesFile = new File(tracesDir, name);
6057 if (curTracesFile.exists()) {
6058 if (lastTracesFile != null) {
6059 curTracesFile.renameTo(lastTracesFile);
6060 } else {
6061 curTracesFile.delete();
6062 }
6063 }
6064 lastTracesFile = curTracesFile;
6065 }
6066 tracesFile.renameTo(curTracesFile);
6067 } finally {
6068 StrictMode.setThreadPolicy(oldPolicy);
6069 }
6070 }
6071
Michal Karpinskida34cd42019-04-02 19:46:52 +01006072 boolean isAssociatedCompanionApp(int userId, int uid) {
6073 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6074 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006075 return false;
6076 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006077 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006078 }
6079
Issei Suzuki734bc942019-06-05 13:59:52 +02006080 void notifySingleTaskDisplayEmpty(int displayId) {
6081 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6082 }
6083
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006084 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006085 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006086
6087
Wale Ogunwale98875612018-10-12 07:53:02 -07006088 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6089 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006090
Riddle Hsud93a6c42018-11-29 21:50:06 +08006091 H(Looper looper) {
6092 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006093 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006094
6095 @Override
6096 public void handleMessage(Message msg) {
6097 switch (msg.what) {
6098 case REPORT_TIME_TRACKER_MSG: {
6099 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6100 tracker.deliverResult(mContext);
6101 } break;
6102 }
6103 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006104 }
6105
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006106 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006107 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006108
6109 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006110 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006111 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006112
6113 @Override
6114 public void handleMessage(Message msg) {
6115 switch (msg.what) {
6116 case DISMISS_DIALOG_UI_MSG: {
6117 final Dialog d = (Dialog) msg.obj;
6118 d.dismiss();
6119 break;
6120 }
6121 }
6122 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006123 }
6124
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 final class LocalService extends ActivityTaskManagerInternal {
6126 @Override
6127 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006128 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006129 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006130 }
6131
6132 @Override
6133 public ComponentName getHomeActivityForUser(int userId) {
6134 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006135 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006136 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006137 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006138 }
6139 }
6140
6141 @Override
6142 public void onLocalVoiceInteractionStarted(IBinder activity,
6143 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6144 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006145 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006146 }
6147 }
6148
6149 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006150 public void notifySingleTaskDisplayDrawn(int displayId) {
6151 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6152 }
6153
6154 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 public void notifyAppTransitionFinished() {
6156 synchronized (mGlobalLock) {
6157 mStackSupervisor.notifyAppTransitionDone();
6158 }
6159 }
6160
6161 @Override
6162 public void notifyAppTransitionCancelled() {
6163 synchronized (mGlobalLock) {
6164 mStackSupervisor.notifyAppTransitionDone();
6165 }
6166 }
6167
6168 @Override
6169 public List<IBinder> getTopVisibleActivities() {
6170 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006171 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 }
6173 }
6174
6175 @Override
6176 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6177 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006178 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 }
6180 }
6181
6182 @Override
6183 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6184 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006185 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 final String[] resolvedTypes = new String[intents.length];
6187
6188 // UID of the package on user userId.
6189 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6190 // packageUid may not be initialized.
6191 int packageUid = 0;
6192 final long ident = Binder.clearCallingIdentity();
6193
6194 try {
6195 for (int i = 0; i < intents.length; i++) {
6196 resolvedTypes[i] =
6197 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6198 }
6199
6200 packageUid = AppGlobals.getPackageManager().getPackageUid(
6201 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6202 } catch (RemoteException e) {
6203 // Shouldn't happen.
6204 } finally {
6205 Binder.restoreCallingIdentity(ident);
6206 }
6207
Riddle Hsu591bf612019-02-14 17:55:31 +08006208 return getActivityStartController().startActivitiesInPackage(
6209 packageUid, packageName,
6210 intents, resolvedTypes, null /* resultTo */,
6211 SafeActivityOptions.fromBundle(bOptions), userId,
6212 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6213 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 }
6215
6216 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006217 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6218 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6219 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6220 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006221 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006222 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006223 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006224 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6225 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6226 userId, validateIncomingUser, originatingPendingIntent,
6227 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006228 }
6229 }
6230
6231 @Override
6232 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6233 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6234 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006235 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006236 PendingIntentRecord originatingPendingIntent,
6237 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006238 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006239 synchronized (mGlobalLock) {
6240 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6241 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6242 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006243 validateIncomingUser, originatingPendingIntent,
6244 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006245 }
6246 }
6247
6248 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6250 Intent intent, Bundle options, int userId) {
6251 return ActivityTaskManagerService.this.startActivityAsUser(
6252 caller, callerPacakge, intent,
6253 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6254 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6255 false /*validateIncomingUser*/);
6256 }
6257
6258 @Override
lumark588a3e82018-07-20 18:53:54 +08006259 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006260 synchronized (mGlobalLock) {
6261
6262 // We might change the visibilities here, so prepare an empty app transition which
6263 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006264 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006265 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006266 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006267 return;
6268 }
Louis Chang677921f2019-12-06 16:44:24 +08006269 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006270 final boolean wasTransitionSet =
6271 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006272 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006273 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 }
Louis Chang149d5c82019-12-30 09:47:39 +08006275 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006276
6277 // If there was a transition set already we don't want to interfere with it as we
6278 // might be starting it too early.
6279 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006280 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 }
6282 }
6283 if (callback != null) {
6284 callback.run();
6285 }
6286 }
6287
6288 @Override
6289 public void notifyKeyguardTrustedChanged() {
6290 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006291 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006292 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 }
6294 }
6295 }
6296
6297 /**
6298 * Called after virtual display Id is updated by
6299 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6300 * {@param vrVr2dDisplayId}.
6301 */
6302 @Override
6303 public void setVr2dDisplayId(int vr2dDisplayId) {
6304 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6305 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006306 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006307 }
6308 }
6309
6310 @Override
6311 public void setFocusedActivity(IBinder token) {
6312 synchronized (mGlobalLock) {
6313 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6314 if (r == null) {
6315 throw new IllegalArgumentException(
6316 "setFocusedActivity: No activity record matching token=" + token);
6317 }
Louis Chang19443452018-10-09 12:10:21 +08006318 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006319 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006320 }
6321 }
6322 }
6323
6324 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006326 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006327 }
6328
6329 @Override
6330 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006331 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006332 }
6333
6334 @Override
6335 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006336 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006337 }
6338
6339 @Override
6340 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6341 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6342 }
6343
6344 @Override
6345 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006346 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006347 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006348
6349 @Override
6350 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6351 synchronized (mGlobalLock) {
6352 mActiveVoiceInteractionServiceComponent = component;
6353 }
6354 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006355
6356 @Override
6357 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6358 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6359 return;
6360 }
6361 synchronized (mGlobalLock) {
6362 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6363 if (types == null) {
6364 if (uid < 0) {
6365 return;
6366 }
6367 types = new ArrayMap<>();
6368 mAllowAppSwitchUids.put(userId, types);
6369 }
6370 if (uid < 0) {
6371 types.remove(type);
6372 } else {
6373 types.put(type, uid);
6374 }
6375 }
6376 }
6377
6378 @Override
6379 public void onUserStopped(int userId) {
6380 synchronized (mGlobalLock) {
6381 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6382 mAllowAppSwitchUids.remove(userId);
6383 }
6384 }
6385
6386 @Override
6387 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6388 synchronized (mGlobalLock) {
6389 return ActivityTaskManagerService.this.isGetTasksAllowed(
6390 caller, callingPid, callingUid);
6391 }
6392 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006393
Riddle Hsua0536432019-02-16 00:38:59 +08006394 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006395 @Override
6396 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006397 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006398 mProcessNames.put(proc.mName, proc.mUid, proc);
6399 }
6400 }
6401
Riddle Hsua0536432019-02-16 00:38:59 +08006402 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006403 @Override
6404 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006405 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006406 mProcessNames.remove(name, uid);
6407 }
6408 }
6409
Riddle Hsua0536432019-02-16 00:38:59 +08006410 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006411 @Override
6412 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006413 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006414 if (proc == mHomeProcess) {
6415 mHomeProcess = null;
6416 }
6417 if (proc == mPreviousProcess) {
6418 mPreviousProcess = null;
6419 }
6420 }
6421 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006422
Riddle Hsua0536432019-02-16 00:38:59 +08006423 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006424 @Override
6425 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006426 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006427 return mTopProcessState;
6428 }
6429 }
6430
Riddle Hsua0536432019-02-16 00:38:59 +08006431 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006432 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006433 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006434 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 return proc == mHeavyWeightProcess;
6436 }
6437 }
6438
Riddle Hsua0536432019-02-16 00:38:59 +08006439 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006440 @Override
6441 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006442 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006443 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6444 }
6445 }
6446
6447 @Override
6448 public void finishHeavyWeightApp() {
6449 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006450 if (mHeavyWeightProcess != null) {
6451 mHeavyWeightProcess.finishActivities();
6452 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006453 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6454 mHeavyWeightProcess);
6455 }
6456 }
6457
Riddle Hsua0536432019-02-16 00:38:59 +08006458 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006459 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006460 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006461 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006462 return isSleepingLocked();
6463 }
6464 }
6465
6466 @Override
6467 public boolean isShuttingDown() {
6468 synchronized (mGlobalLock) {
6469 return mShuttingDown;
6470 }
6471 }
6472
6473 @Override
6474 public boolean shuttingDown(boolean booted, int timeout) {
6475 synchronized (mGlobalLock) {
6476 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006477 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006478 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006479 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006480 return mStackSupervisor.shutdownLocked(timeout);
6481 }
6482 }
6483
6484 @Override
6485 public void enableScreenAfterBoot(boolean booted) {
6486 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006487 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006488 mWindowManager.enableScreenAfterBoot();
6489 updateEventDispatchingLocked(booted);
6490 }
6491 }
6492
6493 @Override
6494 public boolean showStrictModeViolationDialog() {
6495 synchronized (mGlobalLock) {
6496 return mShowDialogs && !mSleeping && !mShuttingDown;
6497 }
6498 }
6499
6500 @Override
6501 public void showSystemReadyErrorDialogsIfNeeded() {
6502 synchronized (mGlobalLock) {
6503 try {
6504 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6505 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6506 + " data partition or your device will be unstable.");
6507 mUiHandler.post(() -> {
6508 if (mShowDialogs) {
6509 AlertDialog d = new BaseErrorDialog(mUiContext);
6510 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6511 d.setCancelable(false);
6512 d.setTitle(mUiContext.getText(R.string.android_system_label));
6513 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6514 d.setButton(DialogInterface.BUTTON_POSITIVE,
6515 mUiContext.getText(R.string.ok),
6516 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6517 d.show();
6518 }
6519 });
6520 }
6521 } catch (RemoteException e) {
6522 }
6523
6524 if (!Build.isBuildConsistent()) {
6525 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6526 mUiHandler.post(() -> {
6527 if (mShowDialogs) {
6528 AlertDialog d = new BaseErrorDialog(mUiContext);
6529 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6530 d.setCancelable(false);
6531 d.setTitle(mUiContext.getText(R.string.android_system_label));
6532 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6533 d.setButton(DialogInterface.BUTTON_POSITIVE,
6534 mUiContext.getText(R.string.ok),
6535 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6536 d.show();
6537 }
6538 });
6539 }
6540 }
6541 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006542
6543 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006544 public void onProcessMapped(int pid, WindowProcessController proc) {
6545 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006546 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006547 }
6548 }
6549
6550 @Override
6551 public void onProcessUnMapped(int pid) {
6552 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006553 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006554 }
6555 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006556
6557 @Override
6558 public void onPackageDataCleared(String name) {
6559 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006560 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006561 mAppWarnings.onPackageDataCleared(name);
6562 }
6563 }
6564
6565 @Override
6566 public void onPackageUninstalled(String name) {
6567 synchronized (mGlobalLock) {
6568 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006569 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006570 }
6571 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006572
6573 @Override
6574 public void onPackageAdded(String name, boolean replacing) {
6575 synchronized (mGlobalLock) {
6576 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6577 }
6578 }
6579
6580 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006581 public void onPackageReplaced(ApplicationInfo aInfo) {
6582 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006583 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006584 }
6585 }
6586
6587 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006588 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6589 synchronized (mGlobalLock) {
6590 return compatibilityInfoForPackageLocked(ai);
6591 }
6592 }
6593
Yunfan Chen75157d72018-07-27 14:47:21 +09006594 /**
6595 * Set the corresponding display information for the process global configuration. To be
6596 * called when we need to show IME on a different display.
6597 *
6598 * @param pid The process id associated with the IME window.
6599 * @param displayId The ID of the display showing the IME.
6600 */
6601 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006602 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006603 // Don't update process-level configuration for Multi-Client IME process since other
6604 // IMEs on other displays will also receive this configuration change due to IME
6605 // services use the same application config/context.
6606 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006607
Yunfan Chen75157d72018-07-27 14:47:21 +09006608 if (pid == MY_PID || pid < 0) {
6609 if (DEBUG_CONFIGURATION) {
6610 Slog.w(TAG,
6611 "Trying to update display configuration for system/invalid process.");
6612 }
6613 return;
6614 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006615 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006616 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006617 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006618 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006619 // Call might come when display is not yet added or has been removed.
6620 if (DEBUG_CONFIGURATION) {
6621 Slog.w(TAG, "Trying to update display configuration for non-existing "
6622 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006623 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006624 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006625 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006626 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006627 if (process == null) {
6628 if (DEBUG_CONFIGURATION) {
6629 Slog.w(TAG, "Trying to update display configuration for invalid "
6630 + "process, pid=" + pid);
6631 }
6632 return;
6633 }
lumarkddc77fb2019-06-27 22:22:23 +08006634 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006635 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006636 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006637 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006638
6639 @Override
6640 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006641 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006642 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006643 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006644 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006645 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006646 }
6647 }
6648 }
6649
6650 @Override
6651 public void clearPendingResultForActivity(IBinder activityToken,
6652 WeakReference<PendingIntentRecord> pir) {
6653 synchronized (mGlobalLock) {
6654 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6655 if (r != null && r.pendingResults != null) {
6656 r.pendingResults.remove(pir);
6657 }
6658 }
6659 }
6660
6661 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006662 public ActivityTokens getTopActivityForTask(int taskId) {
6663 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006664 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006665 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006666 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6667 + " Requested task not found");
6668 return null;
6669 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006670 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006671 if (activity == null) {
6672 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6673 + " Requested activity not found");
6674 return null;
6675 }
6676 if (!activity.attachedToProcess()) {
6677 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6678 + activity);
6679 return null;
6680 }
6681 return new ActivityTokens(activity.appToken, activity.assistToken,
6682 activity.app.getThread());
6683 }
6684 }
6685
6686 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006687 public IIntentSender getIntentSender(int type, String packageName,
6688 int callingUid, int userId, IBinder token, String resultWho,
6689 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6690 Bundle bOptions) {
6691 synchronized (mGlobalLock) {
6692 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6693 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6694 }
6695 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006696
6697 @Override
6698 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6699 synchronized (mGlobalLock) {
6700 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6701 if (r == null) {
6702 return null;
6703 }
6704 if (r.mServiceConnectionsHolder == null) {
6705 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6706 ActivityTaskManagerService.this, r);
6707 }
6708
6709 return r.mServiceConnectionsHolder;
6710 }
6711 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006712
6713 @Override
6714 public Intent getHomeIntent() {
6715 synchronized (mGlobalLock) {
6716 return ActivityTaskManagerService.this.getHomeIntent();
6717 }
6718 }
6719
6720 @Override
6721 public boolean startHomeActivity(int userId, String reason) {
6722 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006723 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006724 }
6725 }
6726
6727 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006728 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006729 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006730 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006731 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006732 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006733 }
Chilun8b1f1be2019-03-13 17:14:36 +08006734 }
6735
6736 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006737 public boolean startHomeOnAllDisplays(int userId, String reason) {
6738 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006739 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006740 }
6741 }
6742
Riddle Hsua0536432019-02-16 00:38:59 +08006743 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006744 @Override
6745 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006746 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006747 if (mFactoryTest == FACTORY_TEST_OFF) {
6748 return false;
6749 }
6750 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6751 && wpc.mName.equals(mTopComponent.getPackageName())) {
6752 return true;
6753 }
6754 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6755 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6756 }
6757 }
6758
6759 @Override
6760 public void updateTopComponentForFactoryTest() {
6761 synchronized (mGlobalLock) {
6762 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6763 return;
6764 }
6765 final ResolveInfo ri = mContext.getPackageManager()
6766 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6767 final CharSequence errorMsg;
6768 if (ri != null) {
6769 final ActivityInfo ai = ri.activityInfo;
6770 final ApplicationInfo app = ai.applicationInfo;
6771 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6772 mTopAction = Intent.ACTION_FACTORY_TEST;
6773 mTopData = null;
6774 mTopComponent = new ComponentName(app.packageName, ai.name);
6775 errorMsg = null;
6776 } else {
6777 errorMsg = mContext.getResources().getText(
6778 com.android.internal.R.string.factorytest_not_system);
6779 }
6780 } else {
6781 errorMsg = mContext.getResources().getText(
6782 com.android.internal.R.string.factorytest_no_action);
6783 }
6784 if (errorMsg == null) {
6785 return;
6786 }
6787
6788 mTopAction = null;
6789 mTopData = null;
6790 mTopComponent = null;
6791 mUiHandler.post(() -> {
6792 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6793 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006794 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006795 });
6796 }
6797 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798
Riddle Hsua0536432019-02-16 00:38:59 +08006799 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800 @Override
6801 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6802 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006803 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006805 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806
6807 wpc.clearRecentTasks();
6808 wpc.clearActivities();
6809
6810 if (wpc.isInstrumenting()) {
6811 finishInstrumentationCallback.run();
6812 }
6813
Jorim Jaggid0752812018-10-16 16:07:20 +02006814 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006815 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006816 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006817 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006818 // If there was nothing to resume, and we are not already restarting
6819 // this process, but there is a visible activity that is hosted by the
6820 // process...then make sure all visible activities are running, taking
6821 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006822 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006823 !PRESERVE_WINDOWS);
6824 }
6825 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006826 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006828 }
6829 }
6830 }
6831
6832 @Override
6833 public void closeSystemDialogs(String reason) {
6834 enforceNotIsolatedCaller("closeSystemDialogs");
6835
6836 final int pid = Binder.getCallingPid();
6837 final int uid = Binder.getCallingUid();
6838 final long origId = Binder.clearCallingIdentity();
6839 try {
6840 synchronized (mGlobalLock) {
6841 // Only allow this from foreground processes, so that background
6842 // applications can't abuse it to prevent system UI from being shown.
6843 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006844 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 if (!proc.isPerceptible()) {
6846 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6847 + " from background process " + proc);
6848 return;
6849 }
6850 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 mWindowManager.closeSystemDialogs(reason);
6852
Louis Chang149d5c82019-12-30 09:47:39 +08006853 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006855 // Call into AM outside the synchronized block.
6856 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857 } finally {
6858 Binder.restoreCallingIdentity(origId);
6859 }
6860 }
6861
6862 @Override
6863 public void cleanupDisabledPackageComponents(
6864 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6865 synchronized (mGlobalLock) {
6866 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006867 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006868 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006869 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006870 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871 }
6872
6873 // Clean-up disabled tasks
6874 getRecentTasks().cleanupDisabledPackageTasksLocked(
6875 packageName, disabledClasses, userId);
6876 }
6877 }
6878
6879 @Override
6880 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6881 int userId) {
6882 synchronized (mGlobalLock) {
6883
6884 boolean didSomething =
6885 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006886 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006887 null, doit, evenPersistent, userId);
6888 return didSomething;
6889 }
6890 }
6891
6892 @Override
6893 public void resumeTopActivities(boolean scheduleIdle) {
6894 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006895 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006896 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006897 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 }
6899 }
6900 }
6901
Riddle Hsua0536432019-02-16 00:38:59 +08006902 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 @Override
6904 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006905 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6907 }
6908 }
6909
Riddle Hsua0536432019-02-16 00:38:59 +08006910 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006911 @Override
6912 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006913 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006914 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6915 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6916 }
6917 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006918 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006919 } finally {
6920 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6921 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 }
6923 }
6924
6925 @Override
6926 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6927 try {
6928 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6929 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6930 }
6931 } catch (RemoteException ex) {
6932 throw new SecurityException("Fail to check is caller a privileged app", ex);
6933 }
6934
6935 synchronized (mGlobalLock) {
6936 final long ident = Binder.clearCallingIdentity();
6937 try {
6938 if (mAmInternal.shouldConfirmCredentials(userId)) {
6939 if (mKeyguardController.isKeyguardLocked()) {
6940 // Showing launcher to avoid user entering credential twice.
6941 startHomeActivity(currentUserId, "notifyLockedProfile");
6942 }
Louis Chang149d5c82019-12-30 09:47:39 +08006943 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 }
6945 } finally {
6946 Binder.restoreCallingIdentity(ident);
6947 }
6948 }
6949 }
6950
6951 @Override
6952 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6953 mAmInternal.enforceCallingPermission(
6954 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6955
6956 synchronized (mGlobalLock) {
6957 final long ident = Binder.clearCallingIdentity();
6958 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006959 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6960 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006961 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6963 UserHandle.CURRENT);
6964 } finally {
6965 Binder.restoreCallingIdentity(ident);
6966 }
6967 }
6968 }
6969
6970 @Override
6971 public void writeActivitiesToProto(ProtoOutputStream proto) {
6972 synchronized (mGlobalLock) {
6973 // The output proto of "activity --proto activities"
6974 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08006975 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006976 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6977 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 }
6979 }
6980
6981 @Override
6982 public void saveANRState(String reason) {
6983 synchronized (mGlobalLock) {
6984 final StringWriter sw = new StringWriter();
6985 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6986 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6987 if (reason != null) {
6988 pw.println(" Reason: " + reason);
6989 }
6990 pw.println();
6991 getActivityStartController().dump(pw, " ", null);
6992 pw.println();
6993 pw.println("-------------------------------------------------------------------------------");
6994 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6995 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6996 "" /* header */);
6997 pw.println();
6998 pw.close();
6999
7000 mLastANRState = sw.toString();
7001 }
7002 }
7003
7004 @Override
7005 public void clearSavedANRState() {
7006 synchronized (mGlobalLock) {
7007 mLastANRState = null;
7008 }
7009 }
7010
7011 @Override
7012 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7013 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7014 synchronized (mGlobalLock) {
7015 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7016 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7017 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7018 dumpLastANRLocked(pw);
7019 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7020 dumpLastANRTracesLocked(pw);
7021 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7022 dumpActivityStarterLocked(pw, dumpPackage);
7023 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7024 dumpActivityContainersLocked(pw);
7025 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7026 if (getRecentTasks() != null) {
7027 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7028 }
7029 }
7030 }
7031 }
7032
7033 @Override
7034 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7035 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7036 int wakefulness) {
7037 synchronized (mGlobalLock) {
7038 if (mHomeProcess != null && (dumpPackage == null
7039 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7040 if (needSep) {
7041 pw.println();
7042 needSep = false;
7043 }
7044 pw.println(" mHomeProcess: " + mHomeProcess);
7045 }
7046 if (mPreviousProcess != null && (dumpPackage == null
7047 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7048 if (needSep) {
7049 pw.println();
7050 needSep = false;
7051 }
7052 pw.println(" mPreviousProcess: " + mPreviousProcess);
7053 }
7054 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7055 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7056 StringBuilder sb = new StringBuilder(128);
7057 sb.append(" mPreviousProcessVisibleTime: ");
7058 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7059 pw.println(sb);
7060 }
7061 if (mHeavyWeightProcess != null && (dumpPackage == null
7062 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7063 if (needSep) {
7064 pw.println();
7065 needSep = false;
7066 }
7067 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7068 }
7069 if (dumpPackage == null) {
7070 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007071 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 }
7073 if (dumpAll) {
7074 if (dumpPackage == null) {
7075 pw.println(" mConfigWillChange: "
7076 + getTopDisplayFocusedStack().mConfigWillChange);
7077 }
7078 if (mCompatModePackages.getPackages().size() > 0) {
7079 boolean printed = false;
7080 for (Map.Entry<String, Integer> entry
7081 : mCompatModePackages.getPackages().entrySet()) {
7082 String pkg = entry.getKey();
7083 int mode = entry.getValue();
7084 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7085 continue;
7086 }
7087 if (!printed) {
7088 pw.println(" mScreenCompatPackages:");
7089 printed = true;
7090 }
7091 pw.println(" " + pkg + ": " + mode);
7092 }
7093 }
7094 }
7095
7096 if (dumpPackage == null) {
7097 pw.println(" mWakefulness="
7098 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007099 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 if (mRunningVoice != null) {
7101 pw.println(" mRunningVoice=" + mRunningVoice);
7102 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7103 }
7104 pw.println(" mSleeping=" + mSleeping);
7105 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7106 pw.println(" mVrController=" + mVrController);
7107 }
7108 if (mCurAppTimeTracker != null) {
7109 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7110 }
7111 if (mAllowAppSwitchUids.size() > 0) {
7112 boolean printed = false;
7113 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7114 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7115 for (int j = 0; j < types.size(); j++) {
7116 if (dumpPackage == null ||
7117 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7118 if (needSep) {
7119 pw.println();
7120 needSep = false;
7121 }
7122 if (!printed) {
7123 pw.println(" mAllowAppSwitchUids:");
7124 printed = true;
7125 }
7126 pw.print(" User ");
7127 pw.print(mAllowAppSwitchUids.keyAt(i));
7128 pw.print(": Type ");
7129 pw.print(types.keyAt(j));
7130 pw.print(" = ");
7131 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7132 pw.println();
7133 }
7134 }
7135 }
7136 }
7137 if (dumpPackage == null) {
7138 if (mController != null) {
7139 pw.println(" mController=" + mController
7140 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7141 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007142 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7143 pw.println(" mLaunchingActivityWakeLock="
7144 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007145 }
7146
7147 return needSep;
7148 }
7149 }
7150
7151 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007152 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7153 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007154 synchronized (mGlobalLock) {
7155 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007156 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007157 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007158 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7159 if (mRunningVoice != null) {
7160 final long vrToken = proto.start(
7161 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7162 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7163 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007164 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007165 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7166 proto.end(vrToken);
7167 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007168 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007169 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007170 if (mController != null) {
7171 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007172 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7173 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7175 proto.end(token);
7176 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007177 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7178 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007179 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181
7182 if (mHomeProcess != null && (dumpPackage == null
7183 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007184 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007185 }
7186
7187 if (mPreviousProcess != null && (dumpPackage == null
7188 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007189 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7191 }
7192
7193 if (mHeavyWeightProcess != null && (dumpPackage == null
7194 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007195 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007196 }
7197
7198 for (Map.Entry<String, Integer> entry
7199 : mCompatModePackages.getPackages().entrySet()) {
7200 String pkg = entry.getKey();
7201 int mode = entry.getValue();
7202 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7203 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7204 proto.write(PACKAGE, pkg);
7205 proto.write(MODE, mode);
7206 proto.end(compatToken);
7207 }
7208 }
7209
7210 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007211 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007212 }
7213
7214 }
7215 }
7216
7217 @Override
7218 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7219 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7220 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007221 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7222 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 }
7224
7225 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007226 public void dumpForOom(PrintWriter pw) {
7227 synchronized (mGlobalLock) {
7228 pw.println(" mHomeProcess: " + mHomeProcess);
7229 pw.println(" mPreviousProcess: " + mPreviousProcess);
7230 if (mHeavyWeightProcess != null) {
7231 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7232 }
7233 }
7234 }
7235
7236 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007237 public boolean canGcNow() {
7238 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007239 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007240 }
7241 }
7242
Riddle Hsua0536432019-02-16 00:38:59 +08007243 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 @Override
7245 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007246 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007247 if (mRootWindowContainer == null) {
7248 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007249 // oomadj after AMS created.
7250 return null;
7251 }
Louis Chang149d5c82019-12-30 09:47:39 +08007252 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007253 return top != null ? top.app : null;
7254 }
7255 }
7256
Riddle Hsua0536432019-02-16 00:38:59 +08007257 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007258 @Override
7259 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007260 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007261 if (mRootWindowContainer != null) {
7262 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007263 }
7264 }
7265 }
7266
7267 @Override
7268 public void scheduleDestroyAllActivities(String reason) {
7269 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007270 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007271 }
7272 }
7273
7274 @Override
7275 public void removeUser(int userId) {
7276 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007277 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007278 }
7279 }
7280
7281 @Override
7282 public boolean switchUser(int userId, UserState userState) {
7283 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007284 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007285 }
7286 }
7287
7288 @Override
7289 public void onHandleAppCrash(WindowProcessController wpc) {
7290 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007291 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007292 }
7293 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007294
7295 @Override
7296 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7297 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007298 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007299 }
7300 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007301
Riddle Hsua0536432019-02-16 00:38:59 +08007302 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007303 @Override
7304 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007305 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007306 }
7307
Riddle Hsua0536432019-02-16 00:38:59 +08007308 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007309 @Override
7310 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007311 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007312 }
7313
Riddle Hsua0536432019-02-16 00:38:59 +08007314 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007315 @Override
7316 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007317 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007318 }
7319
Riddle Hsua0536432019-02-16 00:38:59 +08007320 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007321 @Override
7322 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007323 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007324 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007325
7326 @Override
7327 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007328 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007329 mPendingTempWhitelist.put(uid, tag);
7330 }
7331 }
7332
7333 @Override
7334 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007335 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007336 mPendingTempWhitelist.remove(uid);
7337 }
7338 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007339
7340 @Override
7341 public boolean handleAppCrashInActivityController(String processName, int pid,
7342 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7343 Runnable killCrashingAppCallback) {
7344 synchronized (mGlobalLock) {
7345 if (mController == null) {
7346 return false;
7347 }
7348
7349 try {
7350 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7351 stackTrace)) {
7352 killCrashingAppCallback.run();
7353 return true;
7354 }
7355 } catch (RemoteException e) {
7356 mController = null;
7357 Watchdog.getInstance().setActivityController(null);
7358 }
7359 return false;
7360 }
7361 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007362
7363 @Override
7364 public void removeRecentTasksByPackageName(String packageName, int userId) {
7365 synchronized (mGlobalLock) {
7366 mRecentTasks.removeTasksByPackageName(packageName, userId);
7367 }
7368 }
7369
7370 @Override
7371 public void cleanupRecentTasksForUser(int userId) {
7372 synchronized (mGlobalLock) {
7373 mRecentTasks.cleanupLocked(userId);
7374 }
7375 }
7376
7377 @Override
7378 public void loadRecentTasksForUser(int userId) {
7379 synchronized (mGlobalLock) {
7380 mRecentTasks.loadUserRecentsLocked(userId);
7381 }
7382 }
7383
7384 @Override
7385 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7386 synchronized (mGlobalLock) {
7387 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7388 }
7389 }
7390
7391 @Override
7392 public void flushRecentTasks() {
7393 mRecentTasks.flush();
7394 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007395
7396 @Override
7397 public WindowProcessController getHomeProcess() {
7398 synchronized (mGlobalLock) {
7399 return mHomeProcess;
7400 }
7401 }
7402
7403 @Override
7404 public WindowProcessController getPreviousProcess() {
7405 synchronized (mGlobalLock) {
7406 return mPreviousProcess;
7407 }
7408 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007409
7410 @Override
7411 public void clearLockedTasks(String reason) {
7412 synchronized (mGlobalLock) {
7413 getLockTaskController().clearLockedTasks(reason);
7414 }
7415 }
7416
7417 @Override
7418 public void updateUserConfiguration() {
7419 synchronized (mGlobalLock) {
7420 final Configuration configuration = new Configuration(getGlobalConfiguration());
7421 final int currentUserId = mAmInternal.getCurrentUserId();
7422 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7423 configuration, currentUserId, Settings.System.canWrite(mContext));
7424 updateConfigurationLocked(configuration, null /* starting */,
7425 false /* initLocale */, false /* persistent */, currentUserId,
7426 false /* deferResume */);
7427 }
7428 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007429
7430 @Override
7431 public boolean canShowErrorDialogs() {
7432 synchronized (mGlobalLock) {
7433 return mShowDialogs && !mSleeping && !mShuttingDown
7434 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7435 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7436 mAmInternal.getCurrentUserId())
7437 && !(UserManager.isDeviceInDemoMode(mContext)
7438 && mAmInternal.getCurrentUser().isDemo());
7439 }
7440 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007441
7442 @Override
7443 public void setProfileApp(String profileApp) {
7444 synchronized (mGlobalLock) {
7445 mProfileApp = profileApp;
7446 }
7447 }
7448
7449 @Override
7450 public void setProfileProc(WindowProcessController wpc) {
7451 synchronized (mGlobalLock) {
7452 mProfileProc = wpc;
7453 }
7454 }
7455
7456 @Override
7457 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7458 synchronized (mGlobalLock) {
7459 mProfilerInfo = profilerInfo;
7460 }
7461 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007462
7463 @Override
7464 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7465 synchronized (mGlobalLock) {
7466 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7467 }
7468 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007469
7470 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007471 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7472 boolean reducedResolution) {
7473 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7474 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007475 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007476
7477 @Override
7478 public boolean isUidForeground(int uid) {
7479 synchronized (mGlobalLock) {
7480 return ActivityTaskManagerService.this.isUidForeground(uid);
7481 }
7482 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007483
7484 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007485 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007486 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007487 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007488 }
7489 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007490
7491 @Override
7492 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007493 // Translate package names into UIDs
7494 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007495 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007496 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7497 if (uid >= 0) {
7498 result.add(uid);
7499 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007500 }
7501 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007502 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007503 }
7504 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007505 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007506}