blob: 882d5c70de25a0b5d189eb612baaf5f5f20146f6 [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;
40import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080054import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080071import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
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 Roskybed2d1b2019-11-05 10:26:24 -0800231import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
237import 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;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
261import com.android.server.am.AppTimeTracker;
262import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700263import com.android.server.am.PendingIntentController;
264import com.android.server.am.PendingIntentRecord;
265import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700266import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700267import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800269import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700270import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700278import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700279import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700280import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800281import java.lang.annotation.ElementType;
282import java.lang.annotation.Retention;
283import java.lang.annotation.RetentionPolicy;
284import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700285import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700288import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400290import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700291import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700292import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700293import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700294import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000295import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700296import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297
298/**
299 * System service for managing activities and their containers (task, stacks, displays,... ).
300 *
301 * {@hide}
302 */
303public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800305 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000306 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700307 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
308 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
309 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
310 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700311 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700312
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700315 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700316 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100317 // How long we permit background activity starts after an activity in the process
318 // started or finished.
319 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320
Wale Ogunwale98875612018-10-12 07:53:02 -0700321 /** Used to indicate that an app transition should be animated. */
322 static final boolean ANIMATE = true;
323
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700324 /** Hardware-reported OpenGLES version. */
325 final int GL_ES_VERSION;
326
Wale Ogunwale31913b52018-10-13 08:29:31 -0700327 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
328 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
329 public static final String DUMP_LASTANR_CMD = "lastanr" ;
330 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
331 public static final String DUMP_STARTER_CMD = "starter" ;
332 public static final String DUMP_CONTAINERS_CMD = "containers" ;
333 public static final String DUMP_RECENTS_CMD = "recents" ;
334 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
335
Wale Ogunwale64258362018-10-16 15:13:37 -0700336 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
337 public static final int RELAUNCH_REASON_NONE = 0;
338 /** This activity is being relaunched due to windowing mode change. */
339 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
340 /** This activity is being relaunched due to a free-resize operation. */
341 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
342
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700343 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700344
Wale Ogunwalef6733932018-06-27 05:14:34 -0700345 /**
346 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
347 * change at runtime. Use mContext for non-UI purposes.
348 */
349 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700351 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700352 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700354 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700355 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800356 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800357 @VisibleForTesting
358 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 PowerManagerInternal mPowerManagerInternal;
360 private UsageStatsManagerInternal mUsageStatsInternal;
361
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700362 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 IntentFirewall mIntentFirewall;
364
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700365 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800366 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700368 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800369 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
370 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
371 *
372 * @see WindowManagerThreadPriorityBooster
373 */
374 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700375 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800376 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700377 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700378 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800379 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700380 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800381 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700382 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** All processes currently running that might have a window organized by name. */
384 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100385 /** All processes we currently have running mapped by pid and uid */
386 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** This is the process holding what we currently consider to be the "home" activity. */
388 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700389 /** The currently running heavy-weight process, if any. */
390 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700391 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /**
393 * This is the process holding the activity the user last visited that is in a different process
394 * from the one they are currently in.
395 */
396 WindowProcessController mPreviousProcess;
397 /** The time at which the previous process was last visible. */
398 long mPreviousProcessVisibleTime;
399
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700400 /** List of intents that were used to start the most recent tasks. */
401 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700402 /** State of external calls telling us if the device is awake or asleep. */
403 private boolean mKeyguardShown = false;
404
405 // Wrapper around VoiceInteractionServiceManager
406 private AssistUtils mAssistUtils;
407
408 // VoiceInteraction session ID that changes for each new request except when
409 // being called for multi-window assist in a single session.
410 private int mViSessionId = 1000;
411
412 // How long to wait in getAssistContextExtras for the activity and foreground services
413 // to respond with the result.
414 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
415
416 // How long top wait when going through the modern assist (which doesn't need to block
417 // on getting this result before starting to launch its UI).
418 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
419
420 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
421 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
422
Alison Cichowlas3e340502018-08-07 17:15:01 -0400423 // Permission tokens are used to temporarily granted a trusted app the ability to call
424 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
425 // showing any appropriate error messages to the user.
426 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
427 10 * MINUTE_IN_MILLIS;
428
429 // How long before the service actually expires a token. This is slightly longer than
430 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
431 // expiration exception.
432 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
433 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
434
435 // How long the service will remember expired tokens, for the purpose of providing error
436 // messaging when a client uses an expired token.
437 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
438 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
439
440 // Activity tokens of system activities that are delegating their call to
441 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
442 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
443
444 // Permission tokens that have expired, but we remember for error reporting.
445 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700447 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
448
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700449 // Keeps track of the active voice interaction service component, notified from
450 // VoiceInteractionManagerService
451 ComponentName mActiveVoiceInteractionServiceComponent;
452
Michal Karpinskida34cd42019-04-02 19:46:52 +0100453 // A map userId and all its companion app uids
454 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000455
Wale Ogunwalee2172292018-10-25 10:11:10 -0700456 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 KeyguardController mKeyguardController;
458 private final ClientLifecycleManager mLifecycleManager;
459 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700460 /** The controller for all operations related to locktask. */
461 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700462 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 boolean mSuppressResizeConfigChanges;
465
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700466 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 new UpdateConfigurationResult();
468
469 static final class UpdateConfigurationResult {
470 // Configuration changes that were updated.
471 int changes;
472 // If the activity was relaunched to match the new configuration.
473 boolean activityRelaunched;
474
475 void reset() {
476 changes = 0;
477 activityRelaunched = false;
478 }
479 }
480
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 private int mConfigurationSeq;
483 // To cache the list of supported system locales
484 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485
486 /**
487 * Temp object used when global and/or display override configuration is updated. It is also
488 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
489 * anyone...
490 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 private Configuration mTempConfig = new Configuration();
492
Wale Ogunwalef6733932018-06-27 05:14:34 -0700493 /** Temporary to avoid allocations. */
494 final StringBuilder mStringBuilder = new StringBuilder(256);
495
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 // Amount of time after a call to stopAppSwitches() during which we will
497 // prevent further untrusted switches from happening.
498 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
499
500 /**
501 * The time at which we will allow normal application switches again,
502 * after a call to {@link #stopAppSwitches()}.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505 /**
506 * This is set to true after the first switch after mAppSwitchesAllowedTime
507 * is set; any switches after that will clear the time.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510
Ricky Wai906af482019-06-03 17:25:28 +0100511 /**
512 * Last stop app switches time, apps finished before this time cannot start background activity
513 * even if they are in grace period.
514 */
515 private long mLastStopAppSwitchesTime;
516
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700517 IActivityController mController = null;
518 boolean mControllerIsAMonkey = false;
519
Wale Ogunwale214f3482018-10-04 11:00:47 -0700520 final int mFactoryTest;
521
522 /** Used to control how we initialize the service. */
523 ComponentName mTopComponent;
524 String mTopAction = Intent.ACTION_MAIN;
525 String mTopData;
526
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800527 /** Profiling app information. */
528 String mProfileApp = null;
529 WindowProcessController mProfileProc = null;
530 ProfilerInfo mProfilerInfo = null;
531
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700533 * Dump of the activity state at the time of the last ANR. Cleared after
534 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
535 */
536 String mLastANRState;
537
538 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539 * Used to retain an update lock when the foreground activity is in
540 * immersive mode.
541 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700542 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Packages that are being allowed to perform unrestricted app switches. Mapping is
546 * User -> Type -> uid.
547 */
548 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
549
550 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700551 private int mThumbnailWidth;
552 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700553
554 /**
555 * Flag that indicates if multi-window is enabled.
556 *
557 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
558 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
559 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
560 * At least one of the forms of multi-window must be enabled in order for this flag to be
561 * initialized to 'true'.
562 *
563 * @see #mSupportsSplitScreenMultiWindow
564 * @see #mSupportsFreeformWindowManagement
565 * @see #mSupportsPictureInPicture
566 * @see #mSupportsMultiDisplay
567 */
568 boolean mSupportsMultiWindow;
569 boolean mSupportsSplitScreenMultiWindow;
570 boolean mSupportsFreeformWindowManagement;
571 boolean mSupportsPictureInPicture;
572 boolean mSupportsMultiDisplay;
573 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700574 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700575
576 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
577
578 // VR Vr2d Display Id.
579 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700580
Wale Ogunwalef6733932018-06-27 05:14:34 -0700581 /**
582 * Set while we are wanting to sleep, to prevent any
583 * activities from being started/resumed.
584 *
585 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
586 *
587 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
588 * while in the sleep state until there is a pending transition out of sleep, in which case
589 * mSleeping is set to false, and remains false while awake.
590 *
591 * Whether mSleeping can quickly toggled between true/false without the device actually
592 * display changing states is undefined.
593 */
594 private boolean mSleeping = false;
595
596 /**
597 * The process state used for processes that are running the top activities.
598 * This changes between TOP and TOP_SLEEPING to following mSleeping.
599 */
600 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
601
Riddle Hsua0022cd2019-09-09 21:12:41 +0800602 @Retention(RetentionPolicy.SOURCE)
603 @IntDef({
604 LAYOUT_REASON_CONFIG_CHANGED,
605 LAYOUT_REASON_VISIBILITY_CHANGED,
606 })
607 @interface LayoutReason {}
608 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
609 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
610
611 /** The reasons to perform surface placement. */
612 @LayoutReason
613 private int mLayoutReasons;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
616 // automatically. Important for devices without direct input devices.
617 private boolean mShowDialogs = true;
618
619 /** Set if we are shutting down the system, similar to sleeping. */
620 boolean mShuttingDown = false;
621
622 /**
623 * We want to hold a wake lock while running a voice interaction session, since
624 * this may happen with the screen off and we need to keep the CPU running to
625 * be able to continue to interact with the user.
626 */
627 PowerManager.WakeLock mVoiceWakeLock;
628
629 /**
630 * Set while we are running a voice interaction. This overrides sleeping while it is active.
631 */
632 IVoiceInteractionSession mRunningVoice;
633
634 /**
635 * The last resumed activity. This is identical to the current resumed activity most
636 * of the time but could be different when we're pausing one activity before we resume
637 * another activity.
638 */
639 ActivityRecord mLastResumedActivity;
640
641 /**
642 * The activity that is currently being traced as the active resumed activity.
643 *
644 * @see #updateResumedAppTrace
645 */
646 private @Nullable ActivityRecord mTracedResumedActivity;
647
648 /** If non-null, we are tracking the time the user spends in the currently focused app. */
649 AppTimeTracker mCurAppTimeTracker;
650
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700651 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700652
Wale Ogunwale53783742018-09-16 10:21:51 -0700653 /**
654 * Packages that the user has asked to have run in screen size
655 * compatibility mode instead of filling the screen.
656 */
657 CompatModePackages mCompatModePackages;
658
Wale Ogunwalef6733932018-06-27 05:14:34 -0700659 private FontScaleSettingObserver mFontScaleSettingObserver;
660
Robert Carr8a2f9132019-11-11 15:03:15 -0800661 /**
662 * Stores the registration and state of TaskOrganizers in use.
663 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800664 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800665
Ricky Wai96f5c352019-04-10 18:40:17 +0100666 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000667
Wale Ogunwalef6733932018-06-27 05:14:34 -0700668 private final class FontScaleSettingObserver extends ContentObserver {
669 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
670 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
671
672 public FontScaleSettingObserver() {
673 super(mH);
674 final ContentResolver resolver = mContext.getContentResolver();
675 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
676 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
677 UserHandle.USER_ALL);
678 }
679
680 @Override
681 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
682 if (mFontScaleUri.equals(uri)) {
683 updateFontScaleIfNeeded(userId);
684 } else if (mHideErrorDialogsUri.equals(uri)) {
685 synchronized (mGlobalLock) {
686 updateShouldShowDialogsLocked(getGlobalConfiguration());
687 }
688 }
689 }
690 }
691
Riddle Hsua0536432019-02-16 00:38:59 +0800692 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
693 @Target(ElementType.METHOD)
694 @Retention(RetentionPolicy.SOURCE)
695 @interface HotPath {
696 int NONE = 0;
697 int OOM_ADJUSTMENT = 1;
698 int LRU_UPDATE = 2;
699 int PROCESS_CHANGE = 3;
700 int caller() default NONE;
701 }
702
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800703 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
704 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900705 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800706 mAmInternal.updateOomAdj();
707 }
708 };
709
Charles Chen8d98dd22018-12-26 17:36:54 +0800710 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
711 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700712 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700713 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700714 mSystemThread = ActivityThread.currentActivityThread();
715 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700716 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800717 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700718 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700719 }
720
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700721 public void onSystemReady() {
722 synchronized (mGlobalLock) {
723 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
724 PackageManager.FEATURE_CANT_SAVE_STATE);
725 mAssistUtils = new AssistUtils(mContext);
726 mVrController.onSystemReady();
727 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700728 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700729 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700730 }
731
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700732 public void onInitPowerManagement() {
733 synchronized (mGlobalLock) {
734 mStackSupervisor.initPowerManagement();
735 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
736 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
737 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
738 mVoiceWakeLock.setReferenceCounted(false);
739 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700740 }
741
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700742 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700743 mFontScaleSettingObserver = new FontScaleSettingObserver();
744 }
745
Wale Ogunwale59507092018-10-29 09:00:30 -0700746 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 final boolean freeformWindowManagement =
748 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
749 || Settings.Global.getInt(
750 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
751
752 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
753 final boolean supportsPictureInPicture = supportsMultiWindow &&
754 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
755 final boolean supportsSplitScreenMultiWindow =
756 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
757 final boolean supportsMultiDisplay = mContext.getPackageManager()
758 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700759 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
760 final boolean forceResizable = Settings.Global.getInt(
761 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700762 final boolean sizeCompatFreeform = Settings.Global.getInt(
763 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764
765 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900766 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700767
768 final Configuration configuration = new Configuration();
769 Settings.System.getConfiguration(resolver, configuration);
770 if (forceRtl) {
771 // This will take care of setting the correct layout direction flags
772 configuration.setLayoutDirection(configuration.locale);
773 }
774
775 synchronized (mGlobalLock) {
776 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700777 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 final boolean multiWindowFormEnabled = freeformWindowManagement
779 || supportsSplitScreenMultiWindow
780 || supportsPictureInPicture
781 || supportsMultiDisplay;
782 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
783 mSupportsMultiWindow = true;
784 mSupportsFreeformWindowManagement = freeformWindowManagement;
785 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
786 mSupportsPictureInPicture = supportsPictureInPicture;
787 mSupportsMultiDisplay = supportsMultiDisplay;
788 } else {
789 mSupportsMultiWindow = false;
790 mSupportsFreeformWindowManagement = false;
791 mSupportsSplitScreenMultiWindow = false;
792 mSupportsPictureInPicture = false;
793 mSupportsMultiDisplay = false;
794 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700795 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700796 // This happens before any activities are started, so we can change global configuration
797 // in-place.
798 updateConfigurationLocked(configuration, null, true);
799 final Configuration globalConfig = getGlobalConfiguration();
800 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
801
802 // Load resources only after the current configuration has been set.
803 final Resources res = mContext.getResources();
804 mThumbnailWidth = res.getDimensionPixelSize(
805 com.android.internal.R.dimen.thumbnail_width);
806 mThumbnailHeight = res.getDimensionPixelSize(
807 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700808 }
809 }
810
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800811 public WindowManagerGlobalLock getGlobalLock() {
812 return mGlobalLock;
813 }
814
Yunfan Chen585f2932019-01-29 16:04:45 +0900815 /** For test purpose only. */
816 @VisibleForTesting
817 public ActivityTaskManagerInternal getAtmInternal() {
818 return mInternal;
819 }
820
Riddle Hsud93a6c42018-11-29 21:50:06 +0800821 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
822 Looper looper) {
823 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700824 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700825 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700826 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800827 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700828 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700829 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700830 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700831
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700834 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700836 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700837 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700838 mKeyguardController = mStackSupervisor.getKeyguardController();
839 }
840
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 public void onActivityManagerInternalAdded() {
842 synchronized (mGlobalLock) {
843 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
844 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
845 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700846 }
847
Yunfan Chen75157d72018-07-27 14:47:21 +0900848 int increaseConfigurationSeqLocked() {
849 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
850 return mConfigurationSeq;
851 }
852
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700853 protected ActivityStackSupervisor createStackSupervisor() {
854 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
855 supervisor.initialize();
856 return supervisor;
857 }
858
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800859 protected AppWarnings createAppWarnings(
860 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
861 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
862 }
863
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700864 public void setWindowManager(WindowManagerService wm) {
865 synchronized (mGlobalLock) {
866 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800867 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800868 mTempConfig.setToDefaults();
869 mTempConfig.setLocales(LocaleList.getDefault());
870 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800871 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700872 mLockTaskController.setWindowManager(wm);
873 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800874 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700875 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700876 }
877
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700878 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
879 synchronized (mGlobalLock) {
880 mUsageStatsInternal = usageStatsManager;
881 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700882 }
883
Wale Ogunwalef6733932018-06-27 05:14:34 -0700884 UserManagerService getUserManager() {
885 if (mUserManager == null) {
886 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
887 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
888 }
889 return mUserManager;
890 }
891
Philip P. Moltmannee295092020-02-10 08:46:26 -0800892 AppOpsManager getAppOpsManager() {
893 if (mAppOpsManager == null) {
894 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700895 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800896 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700897 }
898
899 boolean hasUserRestriction(String restriction, int userId) {
900 return getUserManager().hasUserRestriction(restriction, userId);
901 }
902
Michal Karpinski15486842019-04-25 17:33:42 +0100903 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800904 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
905 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100906 if (mode == AppOpsManager.MODE_DEFAULT) {
907 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
908 == PERMISSION_GRANTED;
909 }
910 return mode == AppOpsManager.MODE_ALLOWED;
911 }
912
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700913 @VisibleForTesting
914 protected void setRecentTasks(RecentTasks recentTasks) {
915 mRecentTasks = recentTasks;
916 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700917 }
918
919 RecentTasks getRecentTasks() {
920 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700921 }
922
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700923 ClientLifecycleManager getLifecycleManager() {
924 return mLifecycleManager;
925 }
926
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700927 ActivityStartController getActivityStartController() {
928 return mActivityStartController;
929 }
930
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700931 TaskChangeNotificationController getTaskChangeNotificationController() {
932 return mTaskChangeNotificationController;
933 }
934
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700935 LockTaskController getLockTaskController() {
936 return mLockTaskController;
937 }
938
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 /**
940 * Return the global configuration used by the process corresponding to the input pid. This is
941 * usually the global configuration with some overrides specific to that process.
942 */
943 Configuration getGlobalConfigurationForCallingPid() {
944 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800945 return getGlobalConfigurationForPid(pid);
946 }
947
948 /**
949 * Return the global configuration used by the process corresponding to the given pid.
950 */
951 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900952 if (pid == MY_PID || pid < 0) {
953 return getGlobalConfiguration();
954 }
955 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100956 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 return app != null ? app.getConfiguration() : getGlobalConfiguration();
958 }
959 }
960
961 /**
962 * Return the device configuration info used by the process corresponding to the input pid.
963 * The value is consistent with the global configuration for the process.
964 */
965 @Override
966 public ConfigurationInfo getDeviceConfigurationInfo() {
967 ConfigurationInfo config = new ConfigurationInfo();
968 synchronized (mGlobalLock) {
969 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
970 config.reqTouchScreen = globalConfig.touchscreen;
971 config.reqKeyboardType = globalConfig.keyboard;
972 config.reqNavigation = globalConfig.navigation;
973 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
974 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
975 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
976 }
977 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
978 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
979 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
980 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700981 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900982 }
983 return config;
984 }
985
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700987 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public static final class Lifecycle extends SystemService {
991 private final ActivityTaskManagerService mService;
992
993 public Lifecycle(Context context) {
994 super(context);
995 mService = new ActivityTaskManagerService(context);
996 }
997
998 @Override
999 public void onStart() {
1000 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001001 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 }
1003
Garfield Tan891146c2018-10-09 12:14:00 -07001004 @Override
1005 public void onUnlockUser(int userId) {
1006 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001007 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001008 }
1009 }
1010
1011 @Override
1012 public void onCleanupUser(int userId) {
1013 synchronized (mService.getGlobalLock()) {
1014 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1015 }
1016 }
1017
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001018 public ActivityTaskManagerService getService() {
1019 return mService;
1020 }
1021 }
1022
1023 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001025 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1026 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1027 Bundle bOptions) {
1028 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1029 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 UserHandle.getCallingUserId());
1031 }
1032
1033 @Override
1034 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001035 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1036 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001037 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001039 enforceNotIsolatedCaller(reason);
1040 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001041 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001042 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001043 callingFeatureId, intents, resolvedTypes, resultTo,
1044 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1045 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 }
1047
1048 @Override
1049 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001050 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1051 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1052 Bundle bOptions, int userId) {
1053 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1054 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 true /*validateIncomingUser*/);
1056 }
1057
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001058 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001059 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1060 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1061 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001062 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001063 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001064
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001065 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1067
1068 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001069 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070 .setCaller(caller)
1071 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001072 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 .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)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001218 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 .setRealCallingPid(-1)
1220 .setRealCallingUid(r.launchedFromUid)
1221 .setActivityOptions(options)
1222 .execute();
1223 Binder.restoreCallingIdentity(origId);
1224
1225 r.finishing = wasFinishing;
1226 if (res != ActivityManager.START_SUCCESS) {
1227 return false;
1228 }
1229 return true;
1230 }
1231 }
1232
1233 @Override
1234 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001235 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1236 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1237 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001238 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001240 enforceNotIsolatedCaller("startActivityAndWait");
1241 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1242 userId, "startActivityAndWait");
1243 // TODO: Switch to user app stacks here.
1244 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1245 .setCaller(caller)
1246 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001247 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001248 .setResolvedType(resolvedType)
1249 .setResultTo(resultTo)
1250 .setResultWho(resultWho)
1251 .setRequestCode(requestCode)
1252 .setStartFlags(startFlags)
1253 .setActivityOptions(bOptions)
1254 .setUserId(userId)
1255 .setProfilerInfo(profilerInfo)
1256 .setWaitResult(res)
1257 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001258 return res;
1259 }
1260
1261 @Override
1262 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001263 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1264 String resultWho, int requestCode, int startFlags, Configuration config,
1265 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001266 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001267 enforceNotIsolatedCaller("startActivityWithConfig");
1268 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1269 "startActivityWithConfig");
1270 // TODO: Switch to user app stacks here.
1271 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1272 .setCaller(caller)
1273 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001274 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001275 .setResolvedType(resolvedType)
1276 .setResultTo(resultTo)
1277 .setResultWho(resultWho)
1278 .setRequestCode(requestCode)
1279 .setStartFlags(startFlags)
1280 .setGlobalConfiguration(config)
1281 .setActivityOptions(bOptions)
1282 .setUserId(userId)
1283 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 }
1285
Robert Carr8a2f9132019-11-11 15:03:15 -08001286 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001287 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1288 int callingUid = Binder.getCallingUid();
1289 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1290 throw new SecurityException("Only the system process can request a permission token, "
1291 + "received request from uid: " + callingUid);
1292 }
1293 IBinder permissionToken = new Binder();
1294 synchronized (mGlobalLock) {
1295 mStartActivitySources.put(permissionToken, delegatorToken);
1296 }
1297
1298 Message expireMsg = PooledLambda.obtainMessage(
1299 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1300 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1301
1302 Message forgetMsg = PooledLambda.obtainMessage(
1303 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1304 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1305
1306 return permissionToken;
1307 }
1308
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 @Override
1310 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1311 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001312 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1313 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001314 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001315 // permission grants) as any app that may launch one of your own activities. So we only
1316 // allow this in two cases:
1317 // 1) The caller is an activity that is part of the core framework, and then only when it
1318 // is running as the system.
1319 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1320 // can only be requested by a system activity, which may then delegate this call to
1321 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 final ActivityRecord sourceRecord;
1323 final int targetUid;
1324 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001325 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 final boolean isResolver;
1327 synchronized (mGlobalLock) {
1328 if (resultTo == null) {
1329 throw new SecurityException("Must be called from an activity");
1330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331 final IBinder sourceToken;
1332 if (permissionToken != null) {
1333 // To even attempt to use a permissionToken, an app must also have this signature
1334 // permission.
1335 mAmInternal.enforceCallingPermission(
1336 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1337 "startActivityAsCaller");
1338 // If called with a permissionToken, we want the sourceRecord from the delegator
1339 // activity that requested this token.
1340 sourceToken = mStartActivitySources.remove(permissionToken);
1341 if (sourceToken == null) {
1342 // Invalid permissionToken, check if it recently expired.
1343 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1344 throw new SecurityException("Called with expired permission token: "
1345 + permissionToken);
1346 } else {
1347 throw new SecurityException("Called with invalid permission token: "
1348 + permissionToken);
1349 }
1350 }
1351 } else {
1352 // This method was called directly by the source.
1353 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001355
Louis Chang149d5c82019-12-30 09:47:39 +08001356 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001357 if (sourceRecord == null) {
1358 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 }
1360 if (sourceRecord.app == null) {
1361 throw new SecurityException("Called without a process attached to activity");
1362 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363
1364 // Whether called directly or from a delegate, the source activity must be from the
1365 // android package.
1366 if (!sourceRecord.info.packageName.equals("android")) {
1367 throw new SecurityException("Must be called from an activity that is "
1368 + "declared in the android package");
1369 }
1370
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001371 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001372 // This is still okay, as long as this activity is running under the
1373 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001374 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001376 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377 + " must be system uid or original calling uid "
1378 + sourceRecord.launchedFromUid);
1379 }
1380 }
1381 if (ignoreTargetSecurity) {
1382 if (intent.getComponent() == null) {
1383 throw new SecurityException(
1384 "Component must be specified with ignoreTargetSecurity");
1385 }
1386 if (intent.getSelector() != null) {
1387 throw new SecurityException(
1388 "Selector not allowed with ignoreTargetSecurity");
1389 }
1390 }
1391 targetUid = sourceRecord.launchedFromUid;
1392 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001393 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 isResolver = sourceRecord.isResolverOrChildActivity();
1395 }
1396
1397 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001398 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 }
1400
1401 // TODO: Switch to user app stacks here.
1402 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001403 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 .setCallingUid(targetUid)
1405 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001406 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 .setResolvedType(resolvedType)
1408 .setResultTo(resultTo)
1409 .setResultWho(resultWho)
1410 .setRequestCode(requestCode)
1411 .setStartFlags(startFlags)
1412 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001413 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1415 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001416 // The target may well be in the background, which would normally prevent it
1417 // from starting an activity. Here we definitely want the start to succeed.
1418 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 .execute();
1420 } catch (SecurityException e) {
1421 // XXX need to figure out how to propagate to original app.
1422 // A SecurityException here is generally actually a fault of the original
1423 // calling activity (such as a fairly granting permissions), so propagate it
1424 // back to them.
1425 /*
1426 StringBuilder msg = new StringBuilder();
1427 msg.append("While launching");
1428 msg.append(intent.toString());
1429 msg.append(": ");
1430 msg.append(e.getMessage());
1431 */
1432 throw e;
1433 }
1434 }
1435
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1437 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001438 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001439 }
1440
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001442 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1443 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1445 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001446 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001447 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 if (session == null || interactor == null) {
1449 throw new NullPointerException("null session or interactor");
1450 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001451 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001453 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 .setCallingUid(callingUid)
1455 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001456 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 .setResolvedType(resolvedType)
1458 .setVoiceSession(session)
1459 .setVoiceInteractor(interactor)
1460 .setStartFlags(startFlags)
1461 .setProfilerInfo(profilerInfo)
1462 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001463 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001464 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .execute();
1466 }
1467
1468 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001469 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1470 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1471 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001472 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001473 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1474 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001476 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 .setCallingUid(callingUid)
1478 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001479 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 .setResolvedType(resolvedType)
1481 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001482 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001483 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 .execute();
1485 }
1486
Riddle Hsu609a8e22019-06-27 16:46:29 -06001487 /**
1488 * Start the recents activity to perform the recents animation.
1489 *
1490 * @param intent The intent to start the recents activity.
1491 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1492 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001494 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1495 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001497 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001498 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001499 final long origId = Binder.clearCallingIdentity();
1500 try {
1501 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001502 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001503 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001504 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001505 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001506
1507 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001509 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001510 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001511 if (recentsAnimationRunner == null) {
1512 anim.preloadRecentsActivity();
1513 } else {
1514 anim.startRecentsActivity(recentsAnimationRunner);
1515 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 }
1517 } finally {
1518 Binder.restoreCallingIdentity(origId);
1519 }
1520 }
1521
1522 @Override
1523 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001524 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001525 "startActivityFromRecents()");
1526
1527 final int callingPid = Binder.getCallingPid();
1528 final int callingUid = Binder.getCallingUid();
1529 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1530 final long origId = Binder.clearCallingIdentity();
1531 try {
1532 synchronized (mGlobalLock) {
1533 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1534 safeOptions);
1535 }
1536 } finally {
1537 Binder.restoreCallingIdentity(origId);
1538 }
1539 }
1540
1541 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001542 * Public API to check if the client is allowed to start an activity on specified display.
1543 *
1544 * If the target display is private or virtual, some restrictions will apply.
1545 *
1546 * @param displayId Target display id.
1547 * @param intent Intent used to launch the activity.
1548 * @param resolvedType The MIME type of the intent.
1549 * @param userId The id of the user for whom the call is made.
1550 * @return {@code true} if a call to start an activity on the target display should succeed and
1551 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1552 */
1553 @Override
1554 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1555 String resolvedType, int userId) {
1556 final int callingUid = Binder.getCallingUid();
1557 final int callingPid = Binder.getCallingPid();
1558 final long origId = Binder.clearCallingIdentity();
1559
1560 try {
1561 // Collect information about the target of the Intent.
1562 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1563 0 /* startFlags */, null /* profilerInfo */, userId,
1564 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1565 UserHandle.USER_NULL));
1566 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1567
1568 synchronized (mGlobalLock) {
1569 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1570 aInfo);
1571 }
1572 } finally {
1573 Binder.restoreCallingIdentity(origId);
1574 }
1575 }
1576
1577 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 * This is the internal entry point for handling Activity.finish().
1579 *
1580 * @param token The Binder token referencing the Activity we want to finish.
1581 * @param resultCode Result code, if any, from this Activity.
1582 * @param resultData Result data (Intent), if any, from this Activity.
1583 * @param finishTask Whether to finish the task associated with this Activity.
1584 *
1585 * @return Returns true if the activity successfully finished, or false if it is still running.
1586 */
1587 @Override
1588 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1589 int finishTask) {
1590 // Refuse possible leaked file descriptors
1591 if (resultData != null && resultData.hasFileDescriptors()) {
1592 throw new IllegalArgumentException("File descriptors passed in Intent");
1593 }
1594
1595 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001596 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 if (r == null) {
1598 return true;
1599 }
1600 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001601 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001602 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 if (rootR == null) {
1604 Slog.w(TAG, "Finishing task with all activities already finished");
1605 }
1606 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1607 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001608 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 return false;
1610 }
1611
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001612 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1613 // We should consolidate.
1614 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001616 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001617 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 if (next != null) {
1619 // ask watcher if this is allowed
1620 boolean resumeOK = true;
1621 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001622 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001624 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 Watchdog.getInstance().setActivityController(null);
1626 }
1627
1628 if (!resumeOK) {
1629 Slog.i(TAG, "Not finishing activity because controller resumed");
1630 return false;
1631 }
1632 }
1633 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001634
1635 // note down that the process has finished an activity and is in background activity
1636 // starts grace period
1637 if (r.app != null) {
1638 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1639 }
1640
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001642 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 try {
1644 boolean res;
1645 final boolean finishWithRootActivity =
1646 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1647 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1648 || (finishWithRootActivity && r == rootR)) {
1649 // If requested, remove the task that is associated to this activity only if it
1650 // was the root activity in the task. The result code and data is ignored
1651 // because we don't support returning them across task boundaries. Also, to
1652 // keep backwards compatibility we remove the task from recents when finishing
1653 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001654 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001655 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001656 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001657 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001658 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001660 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001661 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 if (!res) {
1663 Slog.i(TAG, "Failed to finish by app-request");
1664 }
1665 }
1666 return res;
1667 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001668 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001669 Binder.restoreCallingIdentity(origId);
1670 }
1671 }
1672 }
1673
1674 @Override
1675 public boolean finishActivityAffinity(IBinder token) {
1676 synchronized (mGlobalLock) {
1677 final long origId = Binder.clearCallingIdentity();
1678 try {
1679 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1680 if (r == null) {
1681 return false;
1682 }
1683
1684 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1685 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001686 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001687 return false;
1688 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001689
1690 final PooledFunction p = PooledLambda.obtainFunction(
1691 ActivityRecord::finishIfSameAffinity, r,
1692 PooledLambda.__(ActivityRecord.class));
1693 r.getTask().forAllActivities(
1694 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1695 p.recycle();
1696
Andrii Kuliande93eff2019-07-12 12:21:27 -07001697 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 } finally {
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701 }
1702 }
1703
1704 @Override
1705 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1706 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001707 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001708 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001709 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001710 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1711 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001712 return;
1713 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001714 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1715 false /* processPausingActivities */, config);
1716 if (stopProfiling && r.hasProcess()) {
1717 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 }
1719 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001720 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001721 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001722 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 }
1725
1726 @Override
1727 public final void activityResumed(IBinder token) {
1728 final long origId = Binder.clearCallingIdentity();
1729 synchronized (mGlobalLock) {
1730 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 }
1732 Binder.restoreCallingIdentity(origId);
1733 }
1734
1735 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001736 public final void activityTopResumedStateLost() {
1737 final long origId = Binder.clearCallingIdentity();
1738 synchronized (mGlobalLock) {
1739 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1740 }
1741 Binder.restoreCallingIdentity(origId);
1742 }
1743
1744 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001745 public final void activityPaused(IBinder token) {
1746 final long origId = Binder.clearCallingIdentity();
1747 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001748 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001749 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1750 if (r != null) {
1751 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001753 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001754 }
1755 Binder.restoreCallingIdentity(origId);
1756 }
1757
1758 @Override
1759 public final void activityStopped(IBinder token, Bundle icicle,
1760 PersistableBundle persistentState, CharSequence description) {
1761 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1762
1763 // Refuse possible leaked file descriptors
1764 if (icicle != null && icicle.hasFileDescriptors()) {
1765 throw new IllegalArgumentException("File descriptors passed in Bundle");
1766 }
1767
1768 final long origId = Binder.clearCallingIdentity();
1769
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001770 String restartingName = null;
1771 int restartingUid = 0;
1772 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001774 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001775 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001776 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001777 if (r.attachedToProcess()
1778 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1779 // The activity was requested to restart from
1780 // {@link #restartActivityProcessIfVisible}.
1781 restartingName = r.app.mName;
1782 restartingUid = r.app.mUid;
1783 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001784 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001785 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001786 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
1788
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001789 if (restartingName != null) {
1790 // In order to let the foreground activity can be restarted with its saved state from
1791 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1792 // until the activity reports stopped with the state. And the activity record will be
1793 // kept because the record state is restarting, then the activity will be restarted
1794 // immediately if it is still the top one.
1795 mStackSupervisor.removeRestartTimeouts(r);
1796 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1797 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001798 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001799
1800 Binder.restoreCallingIdentity(origId);
1801 }
1802
1803 @Override
1804 public final void activityDestroyed(IBinder token) {
1805 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1806 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001807 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001808 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001809 try {
1810 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1811 if (activity != null) {
1812 activity.destroyed("activityDestroyed");
1813 }
1814 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001815 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001816 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 }
1818 }
1819 }
1820
1821 @Override
1822 public final void activityRelaunched(IBinder token) {
1823 final long origId = Binder.clearCallingIdentity();
1824 synchronized (mGlobalLock) {
1825 mStackSupervisor.activityRelaunchedLocked(token);
1826 }
1827 Binder.restoreCallingIdentity(origId);
1828 }
1829
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 @Override
1831 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1832 synchronized (mGlobalLock) {
1833 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1834 if (r == null) {
1835 return;
1836 }
1837 final long origId = Binder.clearCallingIdentity();
1838 try {
1839 r.setRequestedOrientation(requestedOrientation);
1840 } finally {
1841 Binder.restoreCallingIdentity(origId);
1842 }
1843 }
1844 }
1845
1846 @Override
1847 public int getRequestedOrientation(IBinder token) {
1848 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001849 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1850 return (r != null)
1851 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 }
1853 }
1854
1855 @Override
1856 public void setImmersive(IBinder token, boolean immersive) {
1857 synchronized (mGlobalLock) {
1858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 throw new IllegalArgumentException();
1861 }
1862 r.immersive = immersive;
1863
1864 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001865 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001867 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 }
1869 }
1870 }
1871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001872 void applyUpdateLockStateLocked(ActivityRecord r) {
1873 // Modifications to the UpdateLock state are done on our handler, outside
1874 // the activity manager's locks. The new state is determined based on the
1875 // state *now* of the relevant activity record. The object is passed to
1876 // the handler solely for logging detail, not to be consulted/modified.
1877 final boolean nextState = r != null && r.immersive;
1878 mH.post(() -> {
1879 if (mUpdateLock.isHeld() != nextState) {
1880 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1881 "Applying new update lock state '" + nextState + "' for " + r);
1882 if (nextState) {
1883 mUpdateLock.acquire();
1884 } else {
1885 mUpdateLock.release();
1886 }
1887 }
1888 });
1889 }
1890
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001891 @Override
1892 public boolean isImmersive(IBinder token) {
1893 synchronized (mGlobalLock) {
1894 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1895 if (r == null) {
1896 throw new IllegalArgumentException();
1897 }
1898 return r.immersive;
1899 }
1900 }
1901
1902 @Override
1903 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001904 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001906 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 return (r != null) ? r.immersive : false;
1908 }
1909 }
1910
1911 @Override
1912 public void overridePendingTransition(IBinder token, String packageName,
1913 int enterAnim, int exitAnim) {
1914 synchronized (mGlobalLock) {
1915 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1916 if (self == null) {
1917 return;
1918 }
1919
1920 final long origId = Binder.clearCallingIdentity();
1921
1922 if (self.isState(
1923 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001924 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001925 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 }
1927
1928 Binder.restoreCallingIdentity(origId);
1929 }
1930 }
1931
1932 @Override
1933 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001936 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 if (r == null) {
1938 return ActivityManager.COMPAT_MODE_UNKNOWN;
1939 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001940 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 }
1942 }
1943
1944 @Override
1945 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001950 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 if (r == null) {
1952 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1953 return;
1954 }
1955 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001956 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 }
1958 }
1959
1960 @Override
1961 public int getLaunchedFromUid(IBinder activityToken) {
1962 ActivityRecord srec;
1963 synchronized (mGlobalLock) {
1964 srec = ActivityRecord.forTokenLocked(activityToken);
1965 }
1966 if (srec == null) {
1967 return -1;
1968 }
1969 return srec.launchedFromUid;
1970 }
1971
1972 @Override
1973 public String getLaunchedFromPackage(IBinder activityToken) {
1974 ActivityRecord srec;
1975 synchronized (mGlobalLock) {
1976 srec = ActivityRecord.forTokenLocked(activityToken);
1977 }
1978 if (srec == null) {
1979 return null;
1980 }
1981 return srec.launchedFromPackage;
1982 }
1983
1984 @Override
1985 public boolean convertFromTranslucent(IBinder token) {
1986 final long origId = Binder.clearCallingIdentity();
1987 try {
1988 synchronized (mGlobalLock) {
1989 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1990 if (r == null) {
1991 return false;
1992 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001993 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 }
1995 } finally {
1996 Binder.restoreCallingIdentity(origId);
1997 }
1998 }
1999
2000 @Override
2001 public boolean convertToTranslucent(IBinder token, Bundle options) {
2002 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2003 final long origId = Binder.clearCallingIdentity();
2004 try {
2005 synchronized (mGlobalLock) {
2006 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2007 if (r == null) {
2008 return false;
2009 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002010 final ActivityRecord under = r.getTask().getActivityBelow(r);
2011 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002012 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2013 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002014 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002015 }
2016 } finally {
2017 Binder.restoreCallingIdentity(origId);
2018 }
2019 }
2020
2021 @Override
2022 public void notifyActivityDrawn(IBinder token) {
2023 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2024 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002025 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002027 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 }
2030 }
2031
2032 @Override
2033 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2034 synchronized (mGlobalLock) {
2035 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2036 if (r == null) {
2037 return;
2038 }
2039 r.reportFullyDrawnLocked(restoredFromBundle);
2040 }
2041 }
2042
2043 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002044 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 synchronized (mGlobalLock) {
2046 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002047 if (stack != null) {
2048 final int displayId = stack.getDisplayId();
2049 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 }
2051 return DEFAULT_DISPLAY;
2052 }
2053 }
2054
2055 @Override
2056 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002057 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 long ident = Binder.clearCallingIdentity();
2059 try {
2060 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002061 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002063 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 }
2065 return null;
2066 }
2067 } finally {
2068 Binder.restoreCallingIdentity(ident);
2069 }
2070 }
2071
2072 @Override
2073 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002074 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2076 final long callingId = Binder.clearCallingIdentity();
2077 try {
2078 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002079 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 if (stack == null) {
2081 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2082 return;
2083 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002084 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002085 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002086 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002087 }
2088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(callingId);
2091 }
2092 }
2093
2094 @Override
2095 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002096 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2098 final long callingId = Binder.clearCallingIdentity();
2099 try {
2100 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002101 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002102 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 if (task == null) {
2104 return;
2105 }
2106 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002107 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002108 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 }
2110 }
2111 } finally {
2112 Binder.restoreCallingIdentity(callingId);
2113 }
2114 }
2115
2116 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002117 public void restartActivityProcessIfVisible(IBinder activityToken) {
2118 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2119 final long callingId = Binder.clearCallingIdentity();
2120 try {
2121 synchronized (mGlobalLock) {
2122 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2123 if (r == null) {
2124 return;
2125 }
2126 r.restartProcessIfVisible();
2127 }
2128 } finally {
2129 Binder.restoreCallingIdentity(callingId);
2130 }
2131 }
2132
2133 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002135 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002136 synchronized (mGlobalLock) {
2137 final long ident = Binder.clearCallingIdentity();
2138 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002139 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 "remove-task");
2141 } finally {
2142 Binder.restoreCallingIdentity(ident);
2143 }
2144 }
2145 }
2146
2147 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002148 public void removeAllVisibleRecentTasks() {
2149 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2150 synchronized (mGlobalLock) {
2151 final long ident = Binder.clearCallingIdentity();
2152 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002153 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002154 } finally {
2155 Binder.restoreCallingIdentity(ident);
2156 }
2157 }
2158 }
2159
2160 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002161 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2162 synchronized (mGlobalLock) {
2163 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2164 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002165 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 }
2167 }
2168 return false;
2169 }
2170
2171 @Override
2172 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2173 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002174
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002175 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002176 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2177 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002178 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002179 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002180 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002181 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182 }
2183 }
2184
2185 /**
2186 * Attempts to move a task backwards in z-order (the order of activities within the task is
2187 * unchanged).
2188 *
2189 * There are several possible results of this call:
2190 * - if the task is locked, then we will show the lock toast
2191 * - if there is a task behind the provided task, then that task is made visible and resumed as
2192 * this task is moved to the back
2193 * - otherwise, if there are no other tasks in the stack:
2194 * - if this task is in the pinned stack, then we remove the stack completely, which will
2195 * have the effect of moving the task to the top or bottom of the fullscreen stack
2196 * (depending on whether it is visible)
2197 * - otherwise, we simply return home and hide this task
2198 *
2199 * @param token A reference to the activity we wish to move
2200 * @param nonRoot If false then this only works if the activity is the root
2201 * of a task; if true it will work for any activity in a task.
2202 * @return Returns true if the move completed, false if not.
2203 */
2204 @Override
2205 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002206 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207 synchronized (mGlobalLock) {
2208 final long origId = Binder.clearCallingIdentity();
2209 try {
2210 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002211 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002213 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002214 }
2215 } finally {
2216 Binder.restoreCallingIdentity(origId);
2217 }
2218 }
2219 return false;
2220 }
2221
2222 @Override
2223 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002224 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225 long ident = Binder.clearCallingIdentity();
2226 Rect rect = new Rect();
2227 try {
2228 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002229 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2231 if (task == null) {
2232 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2233 return rect;
2234 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002235 if (task.getParent() != null) {
2236 rect.set(task.getBounds());
2237 } else if (task.mLastNonFullscreenBounds != null) {
2238 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 }
2240 }
2241 } finally {
2242 Binder.restoreCallingIdentity(ident);
2243 }
2244 return rect;
2245 }
2246
2247 @Override
2248 public ActivityManager.TaskDescription getTaskDescription(int id) {
2249 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002250 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002251 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002252 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2254 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002255 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002256 }
2257 }
2258 return null;
2259 }
2260
2261 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002262 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002263 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Winson Chung7ccc6812020-01-23 16:15:10 -08002264 return setTaskWindowingModeSplitScreenPrimary(taskId,
2265 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002269 synchronized (mGlobalLock) {
2270 final long ident = Binder.clearCallingIdentity();
2271 try {
Evan Roskybed2d1b2019-11-05 10:26:24 -08002272 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2273 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2274 }
Louis Chang149d5c82019-12-30 09:47:39 +08002275 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002276 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002277 if (task == null) {
2278 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002279 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002280 }
2281
2282 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2283 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2284
2285 if (!task.isActivityTypeStandardOrUndefined()) {
2286 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2287 + " non-standard task " + taskId + " to windowing mode="
2288 + windowingMode);
2289 }
2290
2291 final ActivityStack stack = task.getStack();
Evan Roskybed2d1b2019-11-05 10:26:24 -08002292 // Convert some windowing-mode changes into root-task reparents for split-screen.
2293 if (stack.getTile() != null) {
2294 stack.getDisplay().onSplitScreenModeDismissed();
2295 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002296 if (toTop) {
2297 stack.moveToFront("setTaskWindowingMode", task);
2298 }
2299 stack.setWindowingMode(windowingMode);
Evan Roskybed2d1b2019-11-05 10:26:24 -08002300 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2301 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002302 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002303 } finally {
2304 Binder.restoreCallingIdentity(ident);
2305 }
2306 }
2307 }
2308
2309 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002311 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002312 ActivityRecord r = getCallingRecordLocked(token);
2313 return r != null ? r.info.packageName : null;
2314 }
2315 }
2316
2317 @Override
2318 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002319 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320 ActivityRecord r = getCallingRecordLocked(token);
2321 return r != null ? r.intent.getComponent() : null;
2322 }
2323 }
2324
2325 private ActivityRecord getCallingRecordLocked(IBinder token) {
2326 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2327 if (r == null) {
2328 return null;
2329 }
2330 return r.resultTo;
2331 }
2332
2333 @Override
2334 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002335 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336
2337 synchronized (mGlobalLock) {
2338 final long origId = Binder.clearCallingIdentity();
2339 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002340 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002341 } finally {
2342 Binder.restoreCallingIdentity(origId);
2343 }
2344 }
2345 }
2346
Mark Renouf446251d2019-04-26 10:22:41 -04002347 @Override
2348 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2349 synchronized (mGlobalLock) {
2350 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2351 if (r == null) {
2352 return;
2353 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002354 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002355 if (stack != null && stack.isSingleTaskInstance()) {
2356 // Single-task stacks are used for activities which are presented in floating
2357 // windows above full screen activities. Instead of directly finishing the
2358 // task, a task change listener is used to notify SystemUI so the action can be
2359 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002360 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002361 mTaskChangeNotificationController
2362 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2363 } else {
2364 try {
2365 callback.requestFinish();
2366 } catch (RemoteException e) {
2367 Slog.e(TAG, "Failed to invoke request finish callback", e);
2368 }
2369 }
2370 }
2371 }
2372
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 /**
2374 * TODO: Add mController hook
2375 */
2376 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2378 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002379 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380
2381 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2382 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2384 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 }
2386 }
2387
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2389 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002391 final int callingPid = Binder.getCallingPid();
2392 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002393 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002394 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 SafeActivityOptions.abort(options);
2396 return;
2397 }
2398 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002399 WindowProcessController callerApp = null;
2400 if (appThread != null) {
2401 callerApp = getProcessController(appThread);
2402 }
2403 final ActivityStarter starter = getActivityStartController().obtainStarter(
2404 null /* intent */, "moveTaskToFront");
2405 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2406 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002407 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002408 return;
2409 }
2410 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002412 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 if (task == null) {
2414 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002415 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002416 return;
2417 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002418 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002420 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002421 return;
2422 }
2423 ActivityOptions realOptions = options != null
2424 ? options.getOptions(mStackSupervisor)
2425 : null;
2426 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2427 false /* forceNonResizable */);
2428
Wale Ogunwale21e06482019-11-18 05:14:15 -08002429 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 if (topActivity != null) {
2431
2432 // We are reshowing a task, use a starting window to hide the initial draw delay
2433 // so the transition can start earlier.
2434 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2435 true /* taskSwitch */, fromRecents);
2436 }
2437 } finally {
2438 Binder.restoreCallingIdentity(origId);
2439 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002440 }
2441
Ricky Waiaca8a772019-04-04 16:01:06 +01002442 /**
2443 * Return true if callingUid is system, or packageName belongs to that callingUid.
2444 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002445 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002446 try {
2447 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2448 if (packageName == null) {
2449 return false;
2450 }
2451 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2452 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2453 UserHandle.getUserId(callingUid));
2454 return UserHandle.isSameApp(callingUid, uid);
2455 }
2456 } catch (RemoteException e) {
2457 // Should not happen
2458 }
2459 return true;
2460 }
2461
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002462 /**
2463 * Checks that the provided package name matches the current calling UID, throws a security
2464 * exception if it doesn't.
2465 */
2466 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2467 final int callingUid = Binder.getCallingUid();
2468 if (isSameApp(callingUid, packageName)) {
2469 return;
2470 }
2471 final String msg = "Permission Denial: package=" + packageName
2472 + " does not belong to uid=" + callingUid;
2473 Slog.w(TAG, msg);
2474 throw new SecurityException(msg);
2475 }
2476
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002477 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2478 int callingPid, int callingUid, String name) {
2479 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2480 return true;
2481 }
2482
2483 if (getRecentTasks().isCallerRecents(sourceUid)) {
2484 return true;
2485 }
2486
2487 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2488 if (perm == PackageManager.PERMISSION_GRANTED) {
2489 return true;
2490 }
2491 if (checkAllowAppSwitchUid(sourceUid)) {
2492 return true;
2493 }
2494
2495 // If the actual IPC caller is different from the logical source, then
2496 // also see if they are allowed to control app switches.
2497 if (callingUid != -1 && callingUid != sourceUid) {
2498 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2499 if (perm == PackageManager.PERMISSION_GRANTED) {
2500 return true;
2501 }
2502 if (checkAllowAppSwitchUid(callingUid)) {
2503 return true;
2504 }
2505 }
2506
2507 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2508 return false;
2509 }
2510
2511 private boolean checkAllowAppSwitchUid(int uid) {
2512 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2513 if (types != null) {
2514 for (int i = types.size() - 1; i >= 0; i--) {
2515 if (types.valueAt(i).intValue() == uid) {
2516 return true;
2517 }
2518 }
2519 }
2520 return false;
2521 }
2522
2523 @Override
2524 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2525 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2526 "setActivityController()");
2527 synchronized (mGlobalLock) {
2528 mController = controller;
2529 mControllerIsAMonkey = imAMonkey;
2530 Watchdog.getInstance().setActivityController(controller);
2531 }
2532 }
2533
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002534 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002535 synchronized (mGlobalLock) {
2536 return mController != null && mControllerIsAMonkey;
2537 }
2538 }
2539
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 @Override
2541 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2542 synchronized (mGlobalLock) {
2543 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2544 }
2545 }
2546
2547 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002548 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2549 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2550 }
2551
2552 @Override
2553 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2554 @WindowConfiguration.ActivityType int ignoreActivityType,
2555 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2556 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002557 final int callingPid = Binder.getCallingPid();
2558 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002559 final int[] profileIds = getUserManager().getProfileIds(
2560 UserHandle.getUserId(callingUid), true);
2561 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2562 for (int i = 0; i < profileIds.length; i++) {
2563 callingProfileIds.add(profileIds[i]);
2564 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2566
2567 synchronized (mGlobalLock) {
2568 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2569
Nicholas Sauer0259e532019-08-30 08:24:55 -07002570 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002571 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002572 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 }
2574
2575 return list;
2576 }
2577
2578 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002579 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2580 synchronized (mGlobalLock) {
2581 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002582 try {
2583 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2584 if (r == null) return;
2585
2586 final PooledConsumer c = PooledLambda.obtainConsumer(
2587 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2588 r, resultWho, requestCode);
2589 // TODO: This should probably only loop over the task since you need to be in the
2590 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002591 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002592 c.recycle();
2593
2594 updateOomAdj();
2595 } finally {
2596 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002597 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 }
2599 }
2600
2601 @Override
2602 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 ActivityStack stack = ActivityRecord.getStackLocked(token);
2605 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002606 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607 }
2608 return false;
2609 }
2610 }
2611
2612 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002614 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002615 synchronized (mGlobalLock) {
2616 final long ident = Binder.clearCallingIdentity();
2617 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002618 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 if (task == null) {
2620 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2621 return;
2622 }
2623
2624 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2625 + " to stackId=" + stackId + " toTop=" + toTop);
2626
Louis Chang149d5c82019-12-30 09:47:39 +08002627 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 if (stack == null) {
2629 throw new IllegalStateException(
2630 "moveTaskToStack: No stack for stackId=" + stackId);
2631 }
2632 if (!stack.isActivityTypeStandardOrUndefined()) {
2633 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2634 + taskId + " to stack " + stackId);
2635 }
2636 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002637 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2639 }
2640 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2641 "moveTaskToStack");
2642 } finally {
2643 Binder.restoreCallingIdentity(ident);
2644 }
2645 }
2646 }
2647
2648 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002649 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2650 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002651
2652 final long ident = Binder.clearCallingIdentity();
2653 try {
2654 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002655 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002656 if (stack == null) {
2657 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2658 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002659 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002660 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2661 throw new IllegalArgumentException("Stack: " + stackId
2662 + " doesn't support animated resize.");
2663 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002664 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002665 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002666 }
2667 } finally {
2668 Binder.restoreCallingIdentity(ident);
2669 }
2670 }
2671
wilsonshih5c4cf522019-01-25 09:03:47 +08002672 @Override
2673 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2674 int animationDuration) {
2675 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2676
2677 final long ident = Binder.clearCallingIdentity();
2678 try {
2679 synchronized (mGlobalLock) {
2680 if (xOffset == 0 && yOffset == 0) {
2681 return;
2682 }
Louis Chang149d5c82019-12-30 09:47:39 +08002683 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002684 if (stack == null) {
2685 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2686 return;
2687 }
2688 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2689 throw new IllegalArgumentException("Stack: " + stackId
2690 + " doesn't support animated resize.");
2691 }
2692 final Rect destBounds = new Rect();
2693 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002694 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002695 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2696 return;
2697 }
2698 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002699 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002700 animationDuration, false /* fromFullscreen */);
2701 }
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 /**
2707 * Moves the specified task to the primary-split-screen stack.
2708 *
2709 * @param taskId Id of task to move.
2710 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2711 * exist already. See
2712 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2713 * and
2714 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2715 * @param toTop If the task and stack should be moved to the top.
2716 * @param animate Whether we should play an animation for the moving the task.
2717 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2718 * stack. Pass {@code null} to use default bounds.
2719 * @param showRecents If the recents activity should be shown on the other side of the task
2720 * going into split-screen mode.
Winson Chung7ccc6812020-01-23 16:15:10 -08002721 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002722 */
2723 @Override
2724 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2725 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002726 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 "setTaskWindowingModeSplitScreenPrimary()");
2728 synchronized (mGlobalLock) {
2729 final long ident = Binder.clearCallingIdentity();
2730 try {
Evan Roskybed2d1b2019-11-05 10:26:24 -08002731 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2732 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737 }
2738
2739 /**
Evan Roskybed2d1b2019-11-05 10:26:24 -08002740 * Moves the specified task into a split-screen tile.
2741 */
2742 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2743 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2744 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2745 + "split-screen mode: " + windowingMode);
2746 }
2747 if (isInLockTaskMode()) {
2748 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2749 + getLockTaskModeState());
2750 return false;
2751 }
2752
2753 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2754 MATCH_TASK_IN_STACKS_ONLY);
2755 if (task == null) {
2756 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2757 return false;
2758 }
2759 if (!task.isActivityTypeStandardOrUndefined()) {
2760 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2761 + " non-standard task " + taskId + " to split-screen windowing mode");
2762 }
2763
2764 final int prevMode = task.getWindowingMode();
2765 final ActivityStack stack = task.getStack();
2766 TaskTile tile = null;
2767 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2768 tile = stack.getDisplay().getStackAt(i).asTile();
2769 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2770 break;
2771 }
2772 }
2773 if (tile == null) {
2774 throw new IllegalStateException("Can't enter split without associated tile");
2775 }
2776 WindowContainerTransaction wct = new WindowContainerTransaction();
2777 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2778 mTaskOrganizerController.applyContainerTransaction(wct, null);
2779 return prevMode != task.getWindowingMode();
2780 }
2781
2782 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002783 * Removes stacks in the input windowing modes from the system if they are of activity type
2784 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2785 */
2786 @Override
2787 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002789 "removeStacksInWindowingModes()");
2790
2791 synchronized (mGlobalLock) {
2792 final long ident = Binder.clearCallingIdentity();
2793 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002794 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002795 } finally {
2796 Binder.restoreCallingIdentity(ident);
2797 }
2798 }
2799 }
2800
2801 @Override
2802 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002804 "removeStacksWithActivityTypes()");
2805
2806 synchronized (mGlobalLock) {
2807 final long ident = Binder.clearCallingIdentity();
2808 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002809 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002810 } finally {
2811 Binder.restoreCallingIdentity(ident);
2812 }
2813 }
2814 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815
2816 @Override
2817 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2818 int userId) {
2819 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002820 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2821 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002823 final boolean detailed = checkGetTasksPermission(
2824 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2825 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 == PackageManager.PERMISSION_GRANTED;
2827
2828 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002829 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 callingUid);
2831 }
2832 }
2833
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002834 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 @Override
2836 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002837 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 long ident = Binder.clearCallingIdentity();
2839 try {
2840 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002841 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 }
2843 } finally {
2844 Binder.restoreCallingIdentity(ident);
2845 }
2846 }
2847
2848 @Override
2849 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002850 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002851 long ident = Binder.clearCallingIdentity();
2852 try {
2853 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002854 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002855 }
2856 } finally {
2857 Binder.restoreCallingIdentity(ident);
2858 }
2859 }
2860
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002861 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002863 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2864 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2865 long ident = Binder.clearCallingIdentity();
2866 try {
2867 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002868 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002869 }
2870 } finally {
2871 Binder.restoreCallingIdentity(ident);
2872 }
2873 }
2874
2875 @Override
2876 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2877 int displayId) {
2878 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2879 long ident = Binder.clearCallingIdentity();
2880 try {
2881 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002882 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002883 }
2884 } finally {
2885 Binder.restoreCallingIdentity(ident);
2886 }
2887 }
2888
2889 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002891 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 final long callingUid = Binder.getCallingUid();
2893 final long origId = Binder.clearCallingIdentity();
2894 try {
2895 synchronized (mGlobalLock) {
2896 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002897 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2899 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2900 }
2901 } finally {
2902 Binder.restoreCallingIdentity(origId);
2903 }
2904 }
2905
2906 @Override
2907 public void startLockTaskModeByToken(IBinder token) {
2908 synchronized (mGlobalLock) {
2909 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2910 if (r == null) {
2911 return;
2912 }
Louis Changcdec0802019-11-11 11:45:07 +08002913 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 }
2915 }
2916
2917 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002918 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002919 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920 // This makes inner call to look as if it was initiated by system.
2921 long ident = Binder.clearCallingIdentity();
2922 try {
2923 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002924 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002925 MATCH_TASK_IN_STACKS_ONLY);
2926 if (task == null) {
2927 return;
2928 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929
2930 // When starting lock task mode the stack must be in front and focused
2931 task.getStack().moveToFront("startSystemLockTaskMode");
2932 startLockTaskModeLocked(task, true /* isSystemCaller */);
2933 }
2934 } finally {
2935 Binder.restoreCallingIdentity(ident);
2936 }
2937 }
2938
2939 @Override
2940 public void stopLockTaskModeByToken(IBinder token) {
2941 synchronized (mGlobalLock) {
2942 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2943 if (r == null) {
2944 return;
2945 }
Louis Changcdec0802019-11-11 11:45:07 +08002946 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 }
2948 }
2949
2950 /**
2951 * This API should be called by SystemUI only when user perform certain action to dismiss
2952 * lock task mode. We should only dismiss pinned lock task mode in this case.
2953 */
2954 @Override
2955 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002956 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002957 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2958 }
2959
Louis Changcdec0802019-11-11 11:45:07 +08002960 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2962 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2963 return;
2964 }
2965
Louis Chang149d5c82019-12-30 09:47:39 +08002966 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002967 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 throw new IllegalArgumentException("Invalid task, not in foreground");
2969 }
2970
2971 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2972 // system or a specific app.
2973 // * System-initiated requests will only start the pinned mode (screen pinning)
2974 // * App-initiated requests
2975 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2976 // - will start the pinned mode, otherwise
2977 final int callingUid = Binder.getCallingUid();
2978 long ident = Binder.clearCallingIdentity();
2979 try {
2980 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002981 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002983 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 } finally {
2985 Binder.restoreCallingIdentity(ident);
2986 }
2987 }
2988
Louis Changcdec0802019-11-11 11:45:07 +08002989 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 final int callingUid = Binder.getCallingUid();
2991 long ident = Binder.clearCallingIdentity();
2992 try {
2993 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002994 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 }
2996 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2997 // task and jumping straight into a call in the case of emergency call back.
2998 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2999 if (tm != null) {
3000 tm.showInCallScreen(false);
3001 }
3002 } finally {
3003 Binder.restoreCallingIdentity(ident);
3004 }
3005 }
3006
3007 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003008 public void updateLockTaskPackages(int userId, String[] packages) {
3009 final int callingUid = Binder.getCallingUid();
3010 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3011 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3012 "updateLockTaskPackages()");
3013 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003014 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003015 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3016 + Arrays.toString(packages));
3017 getLockTaskController().updateLockTaskPackages(userId, packages);
3018 }
3019 }
3020
3021 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 public boolean isInLockTaskMode() {
3023 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3024 }
3025
3026 @Override
3027 public int getLockTaskModeState() {
3028 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003029 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003030 }
3031 }
3032
3033 @Override
3034 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3035 synchronized (mGlobalLock) {
3036 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3037 if (r != null) {
3038 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003039 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003040 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041 }
3042 }
3043 }
3044
3045 @Override
3046 public Bundle getActivityOptions(IBinder token) {
3047 final long origId = Binder.clearCallingIdentity();
3048 try {
3049 synchronized (mGlobalLock) {
3050 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3051 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003052 final ActivityOptions activityOptions = r.takeOptionsLocked(
3053 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 return activityOptions == null ? null : activityOptions.toBundle();
3055 }
3056 return null;
3057 }
3058 } finally {
3059 Binder.restoreCallingIdentity(origId);
3060 }
3061 }
3062
3063 @Override
3064 public List<IBinder> getAppTasks(String callingPackage) {
3065 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003066 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 long ident = Binder.clearCallingIdentity();
3068 try {
3069 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003070 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 }
3072 } finally {
3073 Binder.restoreCallingIdentity(ident);
3074 }
3075 }
3076
3077 @Override
3078 public void finishVoiceTask(IVoiceInteractionSession session) {
3079 synchronized (mGlobalLock) {
3080 final long origId = Binder.clearCallingIdentity();
3081 try {
3082 // TODO: VI Consider treating local voice interactions and voice tasks
3083 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003084 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 } finally {
3086 Binder.restoreCallingIdentity(origId);
3087 }
3088 }
3089
3090 }
3091
3092 @Override
3093 public boolean isTopOfTask(IBinder token) {
3094 synchronized (mGlobalLock) {
3095 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003096 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097 }
3098 }
3099
3100 @Override
3101 public void notifyLaunchTaskBehindComplete(IBinder token) {
3102 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3103 }
3104
3105 @Override
3106 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003107 mH.post(() -> {
3108 synchronized (mGlobalLock) {
3109 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003110 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003111 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003112 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003113 } catch (RemoteException e) {
3114 }
3115 }
3116 }
3117
3118 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 }
3120
3121 /** Called from an app when assist data is ready. */
3122 @Override
3123 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3124 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003125 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 synchronized (pae) {
3127 pae.result = extras;
3128 pae.structure = structure;
3129 pae.content = content;
3130 if (referrer != null) {
3131 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3132 }
3133 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003134 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003135 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003136 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003137 structure.setHomeActivity(pae.isHome);
3138 }
3139 pae.haveResult = true;
3140 pae.notifyAll();
3141 if (pae.intent == null && pae.receiver == null) {
3142 // Caller is just waiting for the result.
3143 return;
3144 }
3145 }
3146 // We are now ready to launch the assist activity.
3147 IAssistDataReceiver sendReceiver = null;
3148 Bundle sendBundle = null;
3149 synchronized (mGlobalLock) {
3150 buildAssistBundleLocked(pae, extras);
3151 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003152 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 if (!exists) {
3154 // Timed out.
3155 return;
3156 }
3157
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003158 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 // Caller wants result sent back to them.
3160 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003161 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003162 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003163 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3164 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003165 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3166 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3167 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3168 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3169 }
3170 }
3171 if (sendReceiver != null) {
3172 try {
3173 sendReceiver.onHandleAssistData(sendBundle);
3174 } catch (RemoteException e) {
3175 }
3176 return;
3177 }
3178
3179 final long ident = Binder.clearCallingIdentity();
3180 try {
3181 if (TextUtils.equals(pae.intent.getAction(),
3182 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003183 // Start voice interaction through VoiceInteractionManagerService.
3184 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3185 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 } else {
3187 pae.intent.replaceExtras(pae.extras);
3188 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3189 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3190 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003191 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192
3193 try {
3194 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3195 } catch (ActivityNotFoundException e) {
3196 Slog.w(TAG, "No activity to handle assist action.", e);
3197 }
3198 }
3199 } finally {
3200 Binder.restoreCallingIdentity(ident);
3201 }
3202 }
3203
3204 @Override
3205 public int addAppTask(IBinder activityToken, Intent intent,
3206 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3207 final int callingUid = Binder.getCallingUid();
3208 final long callingIdent = Binder.clearCallingIdentity();
3209
3210 try {
3211 synchronized (mGlobalLock) {
3212 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3213 if (r == null) {
3214 throw new IllegalArgumentException("Activity does not exist; token="
3215 + activityToken);
3216 }
3217 ComponentName comp = intent.getComponent();
3218 if (comp == null) {
3219 throw new IllegalArgumentException("Intent " + intent
3220 + " must specify explicit component");
3221 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003222 if (thumbnail.getWidth() != mThumbnailWidth
3223 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 throw new IllegalArgumentException("Bad thumbnail size: got "
3225 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003226 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228 if (intent.getSelector() != null) {
3229 intent.setSelector(null);
3230 }
3231 if (intent.getSourceBounds() != null) {
3232 intent.setSourceBounds(null);
3233 }
3234 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3235 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3236 // The caller has added this as an auto-remove task... that makes no
3237 // sense, so turn off auto-remove.
3238 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3239 }
3240 }
3241 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3242 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3243 if (ainfo.applicationInfo.uid != callingUid) {
3244 throw new SecurityException(
3245 "Can't add task for another application: target uid="
3246 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3247 }
3248
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003249 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003250 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003251 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003252 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003254 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 return INVALID_TASK_ID;
3256 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003257 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003258
3259 // TODO: Send the thumbnail to WM to store it.
3260
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003261 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 }
3263 } finally {
3264 Binder.restoreCallingIdentity(callingIdent);
3265 }
3266 }
3267
3268 @Override
3269 public Point getAppTaskThumbnailSize() {
3270 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003271 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 }
3273 }
3274
3275 @Override
3276 public void setTaskResizeable(int taskId, int resizeableMode) {
3277 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003278 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003279 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3280 if (task == null) {
3281 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3282 return;
3283 }
3284 task.setResizeMode(resizeableMode);
3285 }
3286 }
3287
3288 @Override
3289 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003290 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003291 long ident = Binder.clearCallingIdentity();
3292 try {
3293 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003294 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003295 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 if (task == null) {
3297 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3298 return;
3299 }
3300 // Place the task in the right stack if it isn't there already based on
3301 // the requested bounds.
3302 // The stack transition logic is:
3303 // - a null bounds on a freeform task moves that task to fullscreen
3304 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3305 // that task to freeform
3306 // - otherwise the task is not moved
3307 ActivityStack stack = task.getStack();
3308 if (!task.getWindowConfiguration().canResizeTask()) {
3309 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3310 }
3311 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3312 stack = stack.getDisplay().getOrCreateStack(
3313 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3314 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3315 stack = stack.getDisplay().getOrCreateStack(
3316 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3317 }
3318
3319 // Reparent the task to the right stack if necessary
3320 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3321 if (stack != task.getStack()) {
3322 // Defer resume until the task is resized below
3323 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3324 DEFER_RESUME, "resizeTask");
3325 preserveWindow = false;
3326 }
3327
3328 // After reparenting (which only resizes the task to the stack bounds), resize the
3329 // task to the actual bounds provided
3330 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3331 }
3332 } finally {
3333 Binder.restoreCallingIdentity(ident);
3334 }
3335 }
3336
3337 @Override
3338 public boolean releaseActivityInstance(IBinder token) {
3339 synchronized (mGlobalLock) {
3340 final long origId = Binder.clearCallingIdentity();
3341 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003342 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3343 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 return false;
3345 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003346 r.destroyImmediately(true /* removeFromApp */, "app-req");
3347 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 } finally {
3349 Binder.restoreCallingIdentity(origId);
3350 }
3351 }
3352 }
3353
3354 @Override
3355 public void releaseSomeActivities(IApplicationThread appInt) {
3356 synchronized (mGlobalLock) {
3357 final long origId = Binder.clearCallingIdentity();
3358 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003359 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003360 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(origId);
3363 }
3364 }
3365 }
3366
3367 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003368 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 != PackageManager.PERMISSION_GRANTED) {
3371 throw new SecurityException("Requires permission "
3372 + android.Manifest.permission.DEVICE_POWER);
3373 }
3374
3375 synchronized (mGlobalLock) {
3376 long ident = Binder.clearCallingIdentity();
3377 if (mKeyguardShown != keyguardShowing) {
3378 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003379 final Message msg = PooledLambda.obtainMessage(
3380 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3381 keyguardShowing);
3382 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 }
3384 try {
wilsonshih177261f2019-02-22 12:02:18 +08003385 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003386 } finally {
3387 Binder.restoreCallingIdentity(ident);
3388 }
3389 }
3390
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003391 mH.post(() -> {
3392 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3393 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3394 }
3395 });
3396 }
3397
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003398 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 mH.post(() -> {
3400 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3401 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3402 }
3403 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 }
3405
3406 @Override
3407 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3409 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410
3411 final File passedIconFile = new File(filePath);
3412 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3413 passedIconFile.getName());
3414 if (!legitIconFile.getPath().equals(filePath)
3415 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3416 throw new IllegalArgumentException("Bad file path: " + filePath
3417 + " passed for userId " + userId);
3418 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003419 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 }
3421
3422 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 synchronized (mGlobalLock) {
3426 final long ident = Binder.clearCallingIdentity();
3427 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003428 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 if (stack == null) {
3430 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3431 return;
3432 }
3433 if (!stack.isActivityTypeStandardOrUndefined()) {
3434 throw new IllegalArgumentException(
3435 "Removing non-standard stack is not allowed.");
3436 }
3437 mStackSupervisor.removeStack(stack);
3438 } finally {
3439 Binder.restoreCallingIdentity(ident);
3440 }
3441 }
3442 }
3443
3444 @Override
3445 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003446 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447
3448 synchronized (mGlobalLock) {
3449 final long ident = Binder.clearCallingIdentity();
3450 try {
3451 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3452 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003453 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 } finally {
3455 Binder.restoreCallingIdentity(ident);
3456 }
3457 }
3458 }
3459
3460 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003461 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 synchronized (mGlobalLock) {
3463 long ident = Binder.clearCallingIdentity();
3464 try {
3465 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3466 if (r == null) {
3467 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003468 "toggleFreeformWindowingMode: No activity record matching token="
3469 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 }
3471
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003472 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003473 if (stack == null) {
3474 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3475 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 }
3477
Yunfan Chend967af82019-01-17 18:30:18 +09003478 if (!stack.inFreeformWindowingMode()
3479 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3480 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3481 + "toggle between fullscreen and freeform.");
3482 }
3483
3484 if (stack.inFreeformWindowingMode()) {
3485 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003486 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003487 throw new IllegalStateException("Size-compat windows are currently not"
3488 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003489 } else if (stack.getParent().inFreeformWindowingMode()) {
3490 // If the window is on a freeform display, set it to undefined. It will be
3491 // resolved to freeform and it can adjust windowing mode when the display mode
3492 // changes in runtime.
3493 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003494 } else {
3495 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3496 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
3500 }
3501 }
3502
3503 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3504 @Override
3505 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003508 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 }
3510
3511 /** Unregister a task stack listener so that it stops receiving callbacks. */
3512 @Override
3513 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003516 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 @Override
3520 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3521 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3522 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3523 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3524 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3525 }
3526
3527 @Override
3528 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3529 IBinder activityToken, int flags) {
3530 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3531 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3532 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3533 }
3534
3535 @Override
3536 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3537 Bundle args) {
3538 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3539 true /* focused */, true /* newSessionId */, userHandle, args,
3540 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3541 }
3542
3543 @Override
3544 public Bundle getAssistContextExtras(int requestType) {
3545 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3546 null, null, true /* focused */, true /* newSessionId */,
3547 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3548 if (pae == null) {
3549 return null;
3550 }
3551 synchronized (pae) {
3552 while (!pae.haveResult) {
3553 try {
3554 pae.wait();
3555 } catch (InterruptedException e) {
3556 }
3557 }
3558 }
3559 synchronized (mGlobalLock) {
3560 buildAssistBundleLocked(pae, pae.result);
3561 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003562 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563 }
3564 return pae.extras;
3565 }
3566
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003567 /**
3568 * Binder IPC calls go through the public entry point.
3569 * This can be called with or without the global lock held.
3570 */
3571 private static int checkCallingPermission(String permission) {
3572 return checkPermission(
3573 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3574 }
3575
3576 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003577 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003578 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3579 mAmInternal.enforceCallingPermission(permission, func);
3580 }
3581 }
3582
3583 @VisibleForTesting
3584 int checkGetTasksPermission(String permission, int pid, int uid) {
3585 return checkPermission(permission, pid, uid);
3586 }
3587
3588 static int checkPermission(String permission, int pid, int uid) {
3589 if (permission == null) {
3590 return PackageManager.PERMISSION_DENIED;
3591 }
3592 return checkComponentPermission(permission, pid, uid, -1, true);
3593 }
3594
Wale Ogunwale214f3482018-10-04 11:00:47 -07003595 public static int checkComponentPermission(String permission, int pid, int uid,
3596 int owningUid, boolean exported) {
3597 return ActivityManagerService.checkComponentPermission(
3598 permission, pid, uid, owningUid, exported);
3599 }
3600
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003601 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3602 if (getRecentTasks().isCallerRecents(callingUid)) {
3603 // Always allow the recents component to get tasks
3604 return true;
3605 }
3606
3607 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3608 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3609 if (!allowed) {
3610 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3611 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3612 // Temporary compatibility: some existing apps on the system image may
3613 // still be requesting the old permission and not switched to the new
3614 // one; if so, we'll still allow them full access. This means we need
3615 // to see if they are holding the old permission and are a system app.
3616 try {
3617 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3618 allowed = true;
3619 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3620 + " is using old GET_TASKS but privileged; allowing");
3621 }
3622 } catch (RemoteException e) {
3623 }
3624 }
3625 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3626 + " does not hold REAL_GET_TASKS; limiting output");
3627 }
3628 return allowed;
3629 }
3630
Nicholas Sauer0259e532019-08-30 08:24:55 -07003631 boolean isCrossUserAllowed(int pid, int uid) {
3632 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3633 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3634 }
3635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003636 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3637 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3638 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3639 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003640 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003641 "enqueueAssistContext()");
3642
3643 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003644 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 if (activity == null) {
3646 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3647 return null;
3648 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003649 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3651 return null;
3652 }
3653 if (focused) {
3654 if (activityToken != null) {
3655 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3656 if (activity != caller) {
3657 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3658 + " is not current top " + activity);
3659 return null;
3660 }
3661 }
3662 } else {
3663 activity = ActivityRecord.forTokenLocked(activityToken);
3664 if (activity == null) {
3665 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3666 + " couldn't be found");
3667 return null;
3668 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003669 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003670 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3671 return null;
3672 }
3673 }
3674
3675 PendingAssistExtras pae;
3676 Bundle extras = new Bundle();
3677 if (args != null) {
3678 extras.putAll(args);
3679 }
3680 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003681 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682
3683 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3684 userHandle);
3685 pae.isHome = activity.isActivityTypeHome();
3686
3687 // Increment the sessionId if necessary
3688 if (newSessionId) {
3689 mViSessionId++;
3690 }
3691 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003692 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3693 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003695 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 } catch (RemoteException e) {
3697 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3698 return null;
3699 }
3700 return pae;
3701 }
3702 }
3703
3704 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3705 if (result != null) {
3706 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3707 }
3708 if (pae.hint != null) {
3709 pae.extras.putBoolean(pae.hint, true);
3710 }
3711 }
3712
3713 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3714 IAssistDataReceiver receiver;
3715 synchronized (mGlobalLock) {
3716 mPendingAssistExtras.remove(pae);
3717 receiver = pae.receiver;
3718 }
3719 if (receiver != null) {
3720 // Caller wants result sent back to them.
3721 Bundle sendBundle = new Bundle();
3722 // At least return the receiver extras
3723 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3724 try {
3725 pae.receiver.onHandleAssistData(sendBundle);
3726 } catch (RemoteException e) {
3727 }
3728 }
3729 }
3730
3731 public class PendingAssistExtras extends Binder implements Runnable {
3732 public final ActivityRecord activity;
3733 public boolean isHome;
3734 public final Bundle extras;
3735 public final Intent intent;
3736 public final String hint;
3737 public final IAssistDataReceiver receiver;
3738 public final int userHandle;
3739 public boolean haveResult = false;
3740 public Bundle result = null;
3741 public AssistStructure structure = null;
3742 public AssistContent content = null;
3743 public Bundle receiverExtras;
3744
3745 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3746 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3747 int _userHandle) {
3748 activity = _activity;
3749 extras = _extras;
3750 intent = _intent;
3751 hint = _hint;
3752 receiver = _receiver;
3753 receiverExtras = _receiverExtras;
3754 userHandle = _userHandle;
3755 }
3756
3757 @Override
3758 public void run() {
3759 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3760 synchronized (this) {
3761 haveResult = true;
3762 notifyAll();
3763 }
3764 pendingAssistExtrasTimedOut(this);
3765 }
3766 }
3767
3768 @Override
3769 public boolean isAssistDataAllowedOnCurrentActivity() {
3770 int userId;
3771 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003772 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003773 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3774 return false;
3775 }
3776
Wale Ogunwale21e06482019-11-18 05:14:15 -08003777 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003778 if (activity == null) {
3779 return false;
3780 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003781 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 }
3783 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3784 }
3785
3786 @Override
3787 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3788 long ident = Binder.clearCallingIdentity();
3789 try {
3790 synchronized (mGlobalLock) {
3791 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003792 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 if (top != caller) {
3794 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3795 + " is not current top " + top);
3796 return false;
3797 }
3798 if (!top.nowVisible) {
3799 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3800 + " is not visible");
3801 return false;
3802 }
3803 }
3804 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3805 token);
3806 } finally {
3807 Binder.restoreCallingIdentity(ident);
3808 }
3809 }
3810
3811 @Override
3812 public boolean isRootVoiceInteraction(IBinder token) {
3813 synchronized (mGlobalLock) {
3814 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3815 if (r == null) {
3816 return false;
3817 }
3818 return r.rootVoiceInteraction;
3819 }
3820 }
3821
Wale Ogunwalef6733932018-06-27 05:14:34 -07003822 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3823 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3824 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3825 if (activityToCallback == null) return;
3826 activityToCallback.setVoiceSessionLocked(voiceSession);
3827
3828 // Inform the activity
3829 try {
3830 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3831 voiceInteractor);
3832 long token = Binder.clearCallingIdentity();
3833 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003834 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003835 } finally {
3836 Binder.restoreCallingIdentity(token);
3837 }
3838 // TODO: VI Should we cache the activity so that it's easier to find later
3839 // rather than scan through all the stacks and activities?
3840 } catch (RemoteException re) {
3841 activityToCallback.clearVoiceSessionLocked();
3842 // TODO: VI Should this terminate the voice session?
3843 }
3844 }
3845
3846 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3847 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3848 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3849 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3850 boolean wasRunningVoice = mRunningVoice != null;
3851 mRunningVoice = session;
3852 if (!wasRunningVoice) {
3853 mVoiceWakeLock.acquire();
3854 updateSleepIfNeededLocked();
3855 }
3856 }
3857 }
3858
3859 void finishRunningVoiceLocked() {
3860 if (mRunningVoice != null) {
3861 mRunningVoice = null;
3862 mVoiceWakeLock.release();
3863 updateSleepIfNeededLocked();
3864 }
3865 }
3866
3867 @Override
3868 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3869 synchronized (mGlobalLock) {
3870 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3871 if (keepAwake) {
3872 mVoiceWakeLock.acquire();
3873 } else {
3874 mVoiceWakeLock.release();
3875 }
3876 }
3877 }
3878 }
3879
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 @Override
3881 public ComponentName getActivityClassForToken(IBinder token) {
3882 synchronized (mGlobalLock) {
3883 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3884 if (r == null) {
3885 return null;
3886 }
3887 return r.intent.getComponent();
3888 }
3889 }
3890
3891 @Override
3892 public String getPackageForToken(IBinder token) {
3893 synchronized (mGlobalLock) {
3894 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3895 if (r == null) {
3896 return null;
3897 }
3898 return r.packageName;
3899 }
3900 }
3901
3902 @Override
3903 public void showLockTaskEscapeMessage(IBinder token) {
3904 synchronized (mGlobalLock) {
3905 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3906 if (r == null) {
3907 return;
3908 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003909 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003910 }
3911 }
3912
3913 @Override
3914 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003915 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 final long token = Binder.clearCallingIdentity();
3917 try {
3918 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003919 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 }
3921 } finally {
3922 Binder.restoreCallingIdentity(token);
3923 }
3924 }
3925
3926 /**
3927 * Try to place task to provided position. The final position might be different depending on
3928 * current user and stacks state. The task will be moved to target stack if it's currently in
3929 * different stack.
3930 */
3931 @Override
3932 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003933 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003934 synchronized (mGlobalLock) {
3935 long ident = Binder.clearCallingIdentity();
3936 try {
3937 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3938 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003939 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 if (task == null) {
3941 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3942 + taskId);
3943 }
3944
Louis Chang149d5c82019-12-30 09:47:39 +08003945 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946
3947 if (stack == null) {
3948 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3949 + stackId);
3950 }
3951 if (!stack.isActivityTypeStandardOrUndefined()) {
3952 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3953 + " the position of task " + taskId + " in/to non-standard stack");
3954 }
3955
3956 // TODO: Have the callers of this API call a separate reparent method if that is
3957 // what they intended to do vs. having this method also do reparenting.
3958 if (task.getStack() == stack) {
3959 // Change position in current stack.
3960 stack.positionChildAt(task, position);
3961 } else {
3962 // Reparent to new stack.
3963 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3964 !DEFER_RESUME, "positionTaskInStack");
3965 }
3966 } finally {
3967 Binder.restoreCallingIdentity(ident);
3968 }
3969 }
3970 }
3971
3972 @Override
3973 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3974 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3975 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003976 + Arrays.toString(horizontalSizeConfiguration) + " "
3977 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 synchronized (mGlobalLock) {
3979 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3980 if (record == null) {
3981 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3982 + "found for: " + token);
3983 }
3984 record.setSizeConfigurations(horizontalSizeConfiguration,
3985 verticalSizeConfigurations, smallestSizeConfigurations);
3986 }
3987 }
3988
3989 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 * Dismisses Pip
3991 * @param animate True if the dismissal should be animated.
3992 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3993 * default animation duration should be used.
3994 */
3995 @Override
3996 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003997 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 final long ident = Binder.clearCallingIdentity();
3999 try {
4000 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004001 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004002 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 if (stack == null) {
4004 Slog.w(TAG, "dismissPip: pinned stack not found.");
4005 return;
4006 }
4007 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4008 throw new IllegalArgumentException("Stack: " + stack
4009 + " doesn't support animated resize.");
4010 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004011 /**
4012 * TODO(b/146594635): Remove all PIP animation code from WM
4013 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4014 */
4015 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004016 stack.animateResizePinnedStack(null /* destBounds */,
4017 null /* sourceHintBounds */, animationDuration,
4018 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004020 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 }
4022 }
4023 } finally {
4024 Binder.restoreCallingIdentity(ident);
4025 }
4026 }
4027
4028 @Override
4029 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 synchronized (mGlobalLock) {
4032 mSuppressResizeConfigChanges = suppress;
4033 }
4034 }
4035
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 @Override
4037 // TODO: API should just be about changing windowing modes...
4038 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004039 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 "moveTasksToFullscreenStack()");
4041 synchronized (mGlobalLock) {
4042 final long origId = Binder.clearCallingIdentity();
4043 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004044 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 if (stack != null){
4046 if (!stack.isActivityTypeStandardOrUndefined()) {
4047 throw new IllegalArgumentException(
4048 "You can't move tasks from non-standard stacks.");
4049 }
4050 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4051 }
4052 } finally {
4053 Binder.restoreCallingIdentity(origId);
4054 }
4055 }
4056 }
4057
4058 /**
4059 * Moves the top activity in the input stackId to the pinned stack.
4060 *
4061 * @param stackId Id of stack to move the top activity to pinned stack.
4062 * @param bounds Bounds to use for pinned stack.
4063 *
4064 * @return True if the top activity of the input stack was successfully moved to the pinned
4065 * stack.
4066 */
4067 @Override
4068 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004069 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004070 "moveTopActivityToPinnedStack()");
4071 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004072 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4074 + "Device doesn't support picture-in-picture mode");
4075 }
4076
4077 long ident = Binder.clearCallingIdentity();
4078 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004079 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 } finally {
4081 Binder.restoreCallingIdentity(ident);
4082 }
4083 }
4084 }
4085
4086 @Override
4087 public boolean isInMultiWindowMode(IBinder token) {
4088 final long origId = Binder.clearCallingIdentity();
4089 try {
4090 synchronized (mGlobalLock) {
4091 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4092 if (r == null) {
4093 return false;
4094 }
4095 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4096 return r.inMultiWindowMode();
4097 }
4098 } finally {
4099 Binder.restoreCallingIdentity(origId);
4100 }
4101 }
4102
4103 @Override
4104 public boolean isInPictureInPictureMode(IBinder token) {
4105 final long origId = Binder.clearCallingIdentity();
4106 try {
4107 synchronized (mGlobalLock) {
4108 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4109 }
4110 } finally {
4111 Binder.restoreCallingIdentity(origId);
4112 }
4113 }
4114
4115 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004116 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4117 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 return false;
4119 }
4120
4121 // If we are animating to fullscreen then we have already dispatched the PIP mode
4122 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004123 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004124 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 }
4126
4127 @Override
4128 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4129 final long origId = Binder.clearCallingIdentity();
4130 try {
4131 synchronized (mGlobalLock) {
4132 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4133 "enterPictureInPictureMode", token, params);
4134
4135 // If the activity is already in picture in picture mode, then just return early
4136 if (isInPictureInPictureMode(r)) {
4137 return true;
4138 }
4139
4140 // Activity supports picture-in-picture, now check that we can enter PiP at this
4141 // point, if it is
4142 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4143 false /* beforeStopping */)) {
4144 return false;
4145 }
4146
4147 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004148 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004149 if (r.getParent() == null) {
4150 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4151 return;
4152 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004153 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004154 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004155 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4156 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4157 // Adjust the source bounds by the insets for the transition down
4158 final Rect sourceBounds = new Rect(
4159 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004160 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004161 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004162 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004163 stack.setPictureInPictureAspectRatio(aspectRatio);
4164 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004165 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4166 r.info.applicationInfo.uid, r.shortComponentName,
4167 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004168 logPictureInPictureArgs(params);
4169 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 };
4171
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004172 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 // If the keyguard is showing or occluded, then try and dismiss it before
4174 // entering picture-in-picture (this will prompt the user to authenticate if the
4175 // device is currently locked).
4176 dismissKeyguard(token, new KeyguardDismissCallback() {
4177 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004178 public void onDismissSucceeded() {
4179 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 }
4181 }, null /* message */);
4182 } else {
4183 // Enter picture in picture immediately otherwise
4184 enterPipRunnable.run();
4185 }
4186 return true;
4187 }
4188 } finally {
4189 Binder.restoreCallingIdentity(origId);
4190 }
4191 }
4192
4193 @Override
4194 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4195 final long origId = Binder.clearCallingIdentity();
4196 try {
4197 synchronized (mGlobalLock) {
4198 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4199 "setPictureInPictureParams", token, params);
4200
4201 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004202 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004203 if (r.inPinnedWindowingMode()) {
4204 // If the activity is already in picture-in-picture, update the pinned stack now
4205 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4206 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004207 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004208 if (!stack.isAnimatingBoundsToFullscreen()) {
4209 stack.setPictureInPictureAspectRatio(
4210 r.pictureInPictureArgs.getAspectRatio());
4211 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4212 }
4213 }
4214 logPictureInPictureArgs(params);
4215 }
4216 } finally {
4217 Binder.restoreCallingIdentity(origId);
4218 }
4219 }
4220
4221 @Override
4222 public int getMaxNumPictureInPictureActions(IBinder token) {
4223 // Currently, this is a static constant, but later, we may change this to be dependent on
4224 // the context of the activity
4225 return 3;
4226 }
4227
4228 private void logPictureInPictureArgs(PictureInPictureParams params) {
4229 if (params.hasSetActions()) {
4230 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4231 params.getActions().size());
4232 }
4233 if (params.hasSetAspectRatio()) {
4234 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4235 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4236 MetricsLogger.action(lm);
4237 }
4238 }
4239
4240 /**
4241 * Checks the state of the system and the activity associated with the given {@param token} to
4242 * verify that picture-in-picture is supported for that activity.
4243 *
4244 * @return the activity record for the given {@param token} if all the checks pass.
4245 */
4246 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4247 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004248 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 throw new IllegalStateException(caller
4250 + ": Device doesn't support picture-in-picture mode.");
4251 }
4252
4253 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4254 if (r == null) {
4255 throw new IllegalStateException(caller
4256 + ": Can't find activity for token=" + token);
4257 }
4258
4259 if (!r.supportsPictureInPicture()) {
4260 throw new IllegalStateException(caller
4261 + ": Current activity does not support picture-in-picture.");
4262 }
4263
4264 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004265 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004266 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004267 final float minAspectRatio = mContext.getResources().getFloat(
4268 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4269 final float maxAspectRatio = mContext.getResources().getFloat(
4270 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4271 throw new IllegalArgumentException(String.format(caller
4272 + ": Aspect ratio is too extreme (must be between %f and %f).",
4273 minAspectRatio, maxAspectRatio));
4274 }
4275
4276 // Truncate the number of actions if necessary
4277 params.truncateActions(getMaxNumPictureInPictureActions(token));
4278
4279 return r;
4280 }
4281
4282 @Override
4283 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004284 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 synchronized (mGlobalLock) {
4286 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4287 if (r == null) {
4288 throw new IllegalArgumentException("Activity does not exist; token="
4289 + activityToken);
4290 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004291 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 }
4293 }
4294
4295 @Override
4296 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4297 Rect tempDockedTaskInsetBounds,
4298 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 long ident = Binder.clearCallingIdentity();
4301 try {
4302 synchronized (mGlobalLock) {
4303 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4304 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4305 PRESERVE_WINDOWS);
4306 }
4307 } finally {
4308 Binder.restoreCallingIdentity(ident);
4309 }
4310 }
4311
4312 @Override
4313 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004314 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 final long ident = Binder.clearCallingIdentity();
4316 try {
4317 synchronized (mGlobalLock) {
4318 mStackSupervisor.setSplitScreenResizing(resizing);
4319 }
4320 } finally {
4321 Binder.restoreCallingIdentity(ident);
4322 }
4323 }
4324
Evan Rosky0037e5f2019-11-05 10:26:24 -08004325 @Override
4326 public ITaskOrganizerController getTaskOrganizerController() {
4327 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4328 "getTaskOrganizerController()");
4329 return mTaskOrganizerController;
4330 }
4331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 /**
4333 * Check that we have the features required for VR-related API calls, and throw an exception if
4334 * not.
4335 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004336 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004337 if (!mContext.getPackageManager().hasSystemFeature(
4338 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4339 throw new UnsupportedOperationException("VR mode not supported on this device!");
4340 }
4341 }
4342
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 @Override
4344 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004345 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346
4347 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4348
4349 ActivityRecord r;
4350 synchronized (mGlobalLock) {
4351 r = ActivityRecord.isInStackLocked(token);
4352 }
4353
4354 if (r == null) {
4355 throw new IllegalArgumentException();
4356 }
4357
4358 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004359 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 VrManagerInternal.NO_ERROR) {
4361 return err;
4362 }
4363
4364 // Clear the binder calling uid since this path may call moveToTask().
4365 final long callingId = Binder.clearCallingIdentity();
4366 try {
4367 synchronized (mGlobalLock) {
4368 r.requestedVrComponent = (enabled) ? packageName : null;
4369
4370 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004371 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004372 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374 return 0;
4375 }
4376 } finally {
4377 Binder.restoreCallingIdentity(callingId);
4378 }
4379 }
4380
4381 @Override
4382 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4383 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4384 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004385 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4387 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4388 }
Louis Changcdec0802019-11-11 11:45:07 +08004389 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 || activity.voiceSession != null) {
4391 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4392 return;
4393 }
4394 if (activity.pendingVoiceInteractionStart) {
4395 Slog.w(TAG, "Pending start of voice interaction already.");
4396 return;
4397 }
4398 activity.pendingVoiceInteractionStart = true;
4399 }
4400 LocalServices.getService(VoiceInteractionManagerInternal.class)
4401 .startLocalVoiceInteraction(callingActivity, options);
4402 }
4403
4404 @Override
4405 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4406 LocalServices.getService(VoiceInteractionManagerInternal.class)
4407 .stopLocalVoiceInteraction(callingActivity);
4408 }
4409
4410 @Override
4411 public boolean supportsLocalVoiceInteraction() {
4412 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4413 .supportsLocalVoiceInteraction();
4414 }
4415
4416 /** Notifies all listeners when the pinned stack animation starts. */
4417 @Override
4418 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004419 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 }
4421
4422 /** Notifies all listeners when the pinned stack animation ends. */
4423 @Override
4424 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004425 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 }
4427
4428 @Override
4429 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 final long ident = Binder.clearCallingIdentity();
4432 try {
4433 synchronized (mGlobalLock) {
4434 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4435 }
4436 } finally {
4437 Binder.restoreCallingIdentity(ident);
4438 }
4439 }
4440
4441 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444
4445 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004446 if (mWindowManager == null) {
4447 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4448 return false;
4449 }
4450
4451 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004453 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 }
4455
Riddle Hsua0022cd2019-09-09 21:12:41 +08004456 mH.sendMessage(PooledLambda.obtainMessage(
4457 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4458 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459
4460 final long origId = Binder.clearCallingIdentity();
4461 try {
4462 if (values != null) {
4463 Settings.System.clearConfiguration(values);
4464 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 UserHandle.USER_NULL, false /* deferResume */,
4467 mTmpUpdateConfigurationResult);
4468 return mTmpUpdateConfigurationResult.changes != 0;
4469 } finally {
4470 Binder.restoreCallingIdentity(origId);
4471 }
4472 }
4473 }
4474
4475 @Override
4476 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4477 CharSequence message) {
4478 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004479 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4481 }
4482 final long callingId = Binder.clearCallingIdentity();
4483 try {
4484 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004485 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486 }
4487 } finally {
4488 Binder.restoreCallingIdentity(callingId);
4489 }
4490 }
4491
4492 @Override
4493 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 "cancelTaskWindowTransition()");
4496 final long ident = Binder.clearCallingIdentity();
4497 try {
4498 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004499 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 MATCH_TASK_IN_STACKS_ONLY);
4501 if (task == null) {
4502 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4503 return;
4504 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004505 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 }
4507 } finally {
4508 Binder.restoreCallingIdentity(ident);
4509 }
4510 }
4511
4512 @Override
4513 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 final long ident = Binder.clearCallingIdentity();
4516 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004517 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 } finally {
4519 Binder.restoreCallingIdentity(ident);
4520 }
4521 }
4522
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004523 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4524 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004525 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004526 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004527 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004528 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4529 if (task == null) {
4530 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4531 return null;
4532 }
4533 }
4534 // Don't call this while holding the lock as this operation might hit the disk.
4535 return task.getSnapshot(reducedResolution, restoreFromDisk);
4536 }
4537
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 @Override
4539 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4540 synchronized (mGlobalLock) {
4541 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4542 if (r == null) {
4543 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4544 + token);
4545 return;
4546 }
4547 final long origId = Binder.clearCallingIdentity();
4548 try {
4549 r.setDisablePreviewScreenshots(disable);
4550 } finally {
4551 Binder.restoreCallingIdentity(origId);
4552 }
4553 }
4554 }
4555
Riddle Hsu440f88b2019-11-06 22:17:35 +08004556 @Override
4557 public void invalidateHomeTaskSnapshot(IBinder token) {
4558 synchronized (mGlobalLock) {
4559 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4560 if (r == null || !r.isActivityTypeHome()) {
4561 return;
4562 }
4563 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4564 }
4565 }
4566
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 /** Return the user id of the last resumed activity. */
4568 @Override
4569 public @UserIdInt
4570 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004571 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004572 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4573 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004574 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004575 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004576 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004577 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 }
4579 }
4580
4581 @Override
4582 public void updateLockTaskFeatures(int userId, int flags) {
4583 final int callingUid = Binder.getCallingUid();
4584 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004585 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004586 "updateLockTaskFeatures()");
4587 }
4588 synchronized (mGlobalLock) {
4589 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4590 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004591 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004592 }
4593 }
4594
4595 @Override
4596 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4597 synchronized (mGlobalLock) {
4598 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4599 if (r == null) {
4600 return;
4601 }
4602 final long origId = Binder.clearCallingIdentity();
4603 try {
4604 r.setShowWhenLocked(showWhenLocked);
4605 } finally {
4606 Binder.restoreCallingIdentity(origId);
4607 }
4608 }
4609 }
4610
4611 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004612 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4613 synchronized (mGlobalLock) {
4614 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4615 if (r == null) {
4616 return;
4617 }
4618 final long origId = Binder.clearCallingIdentity();
4619 try {
4620 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4621 } finally {
4622 Binder.restoreCallingIdentity(origId);
4623 }
4624 }
4625 }
4626
4627 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4629 synchronized (mGlobalLock) {
4630 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4631 if (r == null) {
4632 return;
4633 }
4634 final long origId = Binder.clearCallingIdentity();
4635 try {
4636 r.setTurnScreenOn(turnScreenOn);
4637 } finally {
4638 Binder.restoreCallingIdentity(origId);
4639 }
4640 }
4641 }
4642
4643 @Override
4644 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004645 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004646 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004647 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004648 synchronized (mGlobalLock) {
4649 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4650 if (r == null) {
4651 return;
4652 }
4653 final long origId = Binder.clearCallingIdentity();
4654 try {
4655 r.registerRemoteAnimations(definition);
4656 } finally {
4657 Binder.restoreCallingIdentity(origId);
4658 }
4659 }
4660 }
4661
4662 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004663 public void unregisterRemoteAnimations(IBinder token) {
4664 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4665 "unregisterRemoteAnimations");
4666 synchronized (mGlobalLock) {
4667 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4668 if (r == null) {
4669 return;
4670 }
4671 final long origId = Binder.clearCallingIdentity();
4672 try {
4673 r.unregisterRemoteAnimations();
4674 } finally {
4675 Binder.restoreCallingIdentity(origId);
4676 }
4677 }
4678 }
4679
4680 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004681 public void registerRemoteAnimationForNextActivityStart(String packageName,
4682 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004683 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004684 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004685 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004686 synchronized (mGlobalLock) {
4687 final long origId = Binder.clearCallingIdentity();
4688 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004689 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004690 packageName, adapter);
4691 } finally {
4692 Binder.restoreCallingIdentity(origId);
4693 }
4694 }
4695 }
4696
Evan Rosky966759f2019-01-15 10:33:58 -08004697 @Override
4698 public void registerRemoteAnimationsForDisplay(int displayId,
4699 RemoteAnimationDefinition definition) {
4700 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4701 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004702 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004703 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004704 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004705 if (display == null) {
4706 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4707 return;
4708 }
4709 final long origId = Binder.clearCallingIdentity();
4710 try {
4711 display.mDisplayContent.registerRemoteAnimations(definition);
4712 } finally {
4713 Binder.restoreCallingIdentity(origId);
4714 }
4715 }
4716 }
4717
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004718 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4719 @Override
4720 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4721 synchronized (mGlobalLock) {
4722 final long origId = Binder.clearCallingIdentity();
4723 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004724 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004725 } finally {
4726 Binder.restoreCallingIdentity(origId);
4727 }
4728 }
4729 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004730
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 @Override
4732 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004733 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004734 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004735 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004736 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004737 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 }
4739 }
4740
4741 @Override
4742 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004743 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004744 != PERMISSION_GRANTED) {
4745 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4746 + Binder.getCallingPid()
4747 + ", uid=" + Binder.getCallingUid()
4748 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4749 Slog.w(TAG, msg);
4750 throw new SecurityException(msg);
4751 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004752 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004753 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004754 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004755 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004756 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004757 }
4758 }
4759
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004760 @Override
4761 public void stopAppSwitches() {
4762 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4763 synchronized (mGlobalLock) {
4764 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004765 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004766 mDidAppSwitch = false;
4767 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4768 }
4769 }
4770
4771 @Override
4772 public void resumeAppSwitches() {
4773 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4774 synchronized (mGlobalLock) {
4775 // Note that we don't execute any pending app switches... we will
4776 // let those wait until either the timeout, or the next start
4777 // activity request.
4778 mAppSwitchesAllowedTime = 0;
4779 }
4780 }
4781
Ricky Wai906af482019-06-03 17:25:28 +01004782 long getLastStopAppSwitchesTime() {
4783 return mLastStopAppSwitchesTime;
4784 }
4785
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004786 void onStartActivitySetDidAppSwitch() {
4787 if (mDidAppSwitch) {
4788 // This is the second allowed switch since we stopped switches, so now just generally
4789 // allow switches. Use case:
4790 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4791 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4792 // anyone to switch again).
4793 mAppSwitchesAllowedTime = 0;
4794 } else {
4795 mDidAppSwitch = true;
4796 }
4797 }
4798
4799 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004800 boolean shouldDisableNonVrUiLocked() {
4801 return mVrController.shouldDisableNonVrUiLocked();
4802 }
4803
Wale Ogunwale53783742018-09-16 10:21:51 -07004804 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004805 // 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 +00004806 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004807 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004808 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4809 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004810 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004811 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004812 }
4813 mH.post(() -> {
4814 if (!mVrController.onVrModeChanged(r)) {
4815 return;
4816 }
4817 synchronized (mGlobalLock) {
4818 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4819 mWindowManager.disableNonVrUi(disableNonVrUi);
4820 if (disableNonVrUi) {
4821 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4822 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004823 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004824 }
4825 }
4826 });
4827 }
4828
Wale Ogunwale53783742018-09-16 10:21:51 -07004829 @Override
4830 public int getPackageScreenCompatMode(String packageName) {
4831 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4832 synchronized (mGlobalLock) {
4833 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4834 }
4835 }
4836
4837 @Override
4838 public void setPackageScreenCompatMode(String packageName, int mode) {
4839 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4840 "setPackageScreenCompatMode");
4841 synchronized (mGlobalLock) {
4842 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4843 }
4844 }
4845
4846 @Override
4847 public boolean getPackageAskScreenCompat(String packageName) {
4848 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4849 synchronized (mGlobalLock) {
4850 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4851 }
4852 }
4853
4854 @Override
4855 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4856 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4857 "setPackageAskScreenCompat");
4858 synchronized (mGlobalLock) {
4859 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4860 }
4861 }
4862
Wale Ogunwale64258362018-10-16 15:13:37 -07004863 public static String relaunchReasonToString(int relaunchReason) {
4864 switch (relaunchReason) {
4865 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4866 return "window_resize";
4867 case RELAUNCH_REASON_FREE_RESIZE:
4868 return "free_resize";
4869 default:
4870 return null;
4871 }
4872 }
4873
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004874 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004875 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004876 }
4877
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004878 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004879 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004880 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4881 }
4882
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004883 boolean isKeyguardLocked() {
4884 return mKeyguardController.isKeyguardLocked();
4885 }
4886
Garfield Tan01548632018-11-27 10:15:48 -08004887 /**
4888 * Clears launch params for the given package.
4889 * @param packageNames the names of the packages of which the launch params are to be cleared
4890 */
4891 @Override
4892 public void clearLaunchParamsForPackages(List<String> packageNames) {
4893 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4894 "clearLaunchParamsForPackages");
4895 synchronized (mGlobalLock) {
4896 for (int i = 0; i < packageNames.size(); ++i) {
4897 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4898 }
4899 }
4900 }
4901
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004902 /**
4903 * Makes the display with the given id a single task instance display. I.e the display can only
4904 * contain one task.
4905 */
4906 @Override
4907 public void setDisplayToSingleTaskInstance(int displayId) {
4908 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4909 "setDisplayToSingleTaskInstance");
4910 final long origId = Binder.clearCallingIdentity();
4911 try {
Louis Chang677921f2019-12-06 16:44:24 +08004912 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004913 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004914 if (display != null) {
4915 display.setDisplayToSingleTaskInstance();
4916 }
4917 } finally {
4918 Binder.restoreCallingIdentity(origId);
4919 }
4920 }
4921
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004922 /**
4923 * Requests that an activity should enter picture-in-picture mode if possible.
4924 */
4925 @Override
4926 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4927 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4928 "requestPictureInPictureMode");
4929 final long origId = Binder.clearCallingIdentity();
4930 try {
4931 synchronized (mGlobalLock) {
4932 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4933 if (activity == null) {
4934 return;
4935 }
4936
4937 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4938 "requestPictureInPictureMode", /* beforeStopping */ false);
4939 if (!canEnterPictureInPicture) {
4940 throw new IllegalStateException(
4941 "Requested PIP on an activity that doesn't support it");
4942 }
4943
4944 try {
4945 final ClientTransaction transaction = ClientTransaction.obtain(
4946 activity.app.getThread(),
4947 activity.token);
4948 transaction.addCallback(EnterPipRequestedItem.obtain());
4949 getLifecycleManager().scheduleTransaction(transaction);
4950 } catch (Exception e) {
4951 Slog.w(TAG, "Failed to send enter pip requested item: "
4952 + activity.intent.getComponent(), e);
4953 }
4954 }
4955 } finally {
4956 Binder.restoreCallingIdentity(origId);
4957 }
4958 }
4959
Wale Ogunwale31913b52018-10-13 08:29:31 -07004960 void dumpLastANRLocked(PrintWriter pw) {
4961 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4962 if (mLastANRState == null) {
4963 pw.println(" <no ANR has occurred since boot>");
4964 } else {
4965 pw.println(mLastANRState);
4966 }
4967 }
4968
4969 void dumpLastANRTracesLocked(PrintWriter pw) {
4970 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4971
4972 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4973 if (ArrayUtils.isEmpty(files)) {
4974 pw.println(" <no ANR has occurred since boot>");
4975 return;
4976 }
4977 // Find the latest file.
4978 File latest = null;
4979 for (File f : files) {
4980 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4981 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004982 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004983 }
4984 pw.print("File: ");
4985 pw.print(latest.getName());
4986 pw.println();
4987 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4988 String line;
4989 while ((line = in.readLine()) != null) {
4990 pw.println(line);
4991 }
4992 } catch (IOException e) {
4993 pw.print("Unable to read: ");
4994 pw.print(e);
4995 pw.println();
4996 }
4997 }
4998
4999 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5000 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5001 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5002 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5003 }
5004
5005 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5006 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5007 pw.println(header);
5008
Louis Chang149d5c82019-12-30 09:47:39 +08005009 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005010 dumpPackage);
5011 boolean needSep = printedAnything;
5012
5013 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005014 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005015 " ResumedActivity: ");
5016 if (printed) {
5017 printedAnything = true;
5018 needSep = false;
5019 }
5020
5021 if (dumpPackage == null) {
5022 if (needSep) {
5023 pw.println();
5024 }
5025 printedAnything = true;
5026 mStackSupervisor.dump(pw, " ");
5027 }
5028
5029 if (!printedAnything) {
5030 pw.println(" (nothing)");
5031 }
5032 }
5033
5034 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005035 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005036 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005037 pw.println(" ");
5038 }
5039
5040 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5041 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5042 getActivityStartController().dump(pw, "", dumpPackage);
5043 }
5044
5045 /**
5046 * There are three things that cmd can be:
5047 * - a flattened component name that matches an existing activity
5048 * - the cmd arg isn't the flattened component name of an existing activity:
5049 * dump all activity whose component contains the cmd as a substring
5050 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005051 * <p>
5052 * The caller should not hold lock when calling this method because it will wait for the
5053 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005054 *
5055 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5056 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5057 */
5058 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5059 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5060 ArrayList<ActivityRecord> activities;
5061
5062 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005063 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005064 dumpFocusedStackOnly);
5065 }
5066
5067 if (activities.size() <= 0) {
5068 return false;
5069 }
5070
5071 String[] newArgs = new String[args.length - opti];
5072 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5073
Louis Changcdec0802019-11-11 11:45:07 +08005074 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005075 boolean needSep = false;
5076 for (int i = activities.size() - 1; i >= 0; i--) {
5077 ActivityRecord r = activities.get(i);
5078 if (needSep) {
5079 pw.println();
5080 }
5081 needSep = true;
5082 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005083 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005084 if (lastTask != task) {
5085 lastTask = task;
5086 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005087 pw.print(" id="); pw.print(lastTask.mTaskId);
5088 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005089 if (dumpAll) {
5090 lastTask.dump(pw, " ");
5091 }
5092 }
5093 }
5094 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5095 }
5096 return true;
5097 }
5098
5099 /**
5100 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5101 * there is a thread associated with the activity.
5102 */
5103 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5104 final ActivityRecord r, String[] args, boolean dumpAll) {
5105 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005106 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005107 synchronized (mGlobalLock) {
5108 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5109 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5110 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005111 if (r.hasProcess()) {
5112 pw.println(r.app.getPid());
5113 appThread = r.app.getThread();
5114 } else {
5115 pw.println("(not running)");
5116 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005117 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005118 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005119 }
5120 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005121 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005122 // flush anything that is already in the PrintWriter since the thread is going
5123 // to write to the file descriptor directly
5124 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005125 try (TransferPipe tp = new TransferPipe()) {
5126 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5127 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005128 } catch (IOException e) {
5129 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5130 } catch (RemoteException e) {
5131 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5132 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005133 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005134 }
5135
sanryhuang498e77e2018-12-06 14:57:01 +08005136 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5137 boolean testPssMode) {
5138 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5139 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5140 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005141 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005142 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5143 st.toString());
5144 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005145 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5146 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5147 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005148 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5149 testPssMode);
5150 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005151 }
5152
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005153 int getCurrentUserId() {
5154 return mAmInternal.getCurrentUserId();
5155 }
5156
5157 private void enforceNotIsolatedCaller(String caller) {
5158 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5159 throw new SecurityException("Isolated process not allowed to call " + caller);
5160 }
5161 }
5162
Wale Ogunwalef6733932018-06-27 05:14:34 -07005163 public Configuration getConfiguration() {
5164 Configuration ci;
5165 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005166 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005167 ci.userSetLocale = false;
5168 }
5169 return ci;
5170 }
5171
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 /**
5173 * Current global configuration information. Contains general settings for the entire system,
5174 * also corresponds to the merged configuration of the default display.
5175 */
5176 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005177 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005178 // while initializing process record for system, see {@link
5179 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005180 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005181 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182 }
5183
5184 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5185 boolean initLocale) {
5186 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5187 }
5188
5189 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5190 boolean initLocale, boolean deferResume) {
5191 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5192 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5193 UserHandle.USER_NULL, deferResume);
5194 }
5195
Wale Ogunwale59507092018-10-29 09:00:30 -07005196 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197 final long origId = Binder.clearCallingIdentity();
5198 try {
5199 synchronized (mGlobalLock) {
5200 updateConfigurationLocked(values, null, false, true, userId,
5201 false /* deferResume */);
5202 }
5203 } finally {
5204 Binder.restoreCallingIdentity(origId);
5205 }
5206 }
5207
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005208 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5209 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5210 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5211 deferResume, null /* result */);
5212 }
5213
5214 /**
5215 * Do either or both things: (1) change the current configuration, and (2)
5216 * make sure the given activity is running with the (now) current
5217 * configuration. Returns true if the activity has been left running, or
5218 * false if <var>starting</var> is being destroyed to match the new
5219 * configuration.
5220 *
5221 * @param userId is only used when persistent parameter is set to true to persist configuration
5222 * for that particular user
5223 */
5224 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5225 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5226 ActivityTaskManagerService.UpdateConfigurationResult result) {
5227 int changes = 0;
5228 boolean kept = true;
5229
Riddle Hsua0022cd2019-09-09 21:12:41 +08005230 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 try {
5232 if (values != null) {
5233 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5234 deferResume);
5235 }
5236
5237 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5238 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005239 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240 }
5241
5242 if (result != null) {
5243 result.changes = changes;
5244 result.activityRelaunched = !kept;
5245 }
5246 return kept;
5247 }
5248
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005250 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005252
Louis Chang677921f2019-12-06 16:44:24 +08005253 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005254 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005255
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005256 mTempConfig.setTo(getGlobalConfiguration());
5257 final int changes = mTempConfig.updateFrom(values);
5258 if (changes == 0) {
5259 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5260 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5261 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5262 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005263 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005264 return 0;
5265 }
5266
5267 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5268 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005269 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005270 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005271 values.colorMode,
5272 values.densityDpi,
5273 values.fontScale,
5274 values.hardKeyboardHidden,
5275 values.keyboard,
5276 values.keyboardHidden,
5277 values.mcc,
5278 values.mnc,
5279 values.navigation,
5280 values.navigationHidden,
5281 values.orientation,
5282 values.screenHeightDp,
5283 values.screenLayout,
5284 values.screenWidthDp,
5285 values.smallestScreenWidthDp,
5286 values.touchscreen,
5287 values.uiMode);
5288
5289
5290 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5291 final LocaleList locales = values.getLocales();
5292 int bestLocaleIndex = 0;
5293 if (locales.size() > 1) {
5294 if (mSupportedSystemLocales == null) {
5295 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5296 }
5297 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5298 }
5299 SystemProperties.set("persist.sys.locale",
5300 locales.get(bestLocaleIndex).toLanguageTag());
5301 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005302
5303 final Message m = PooledLambda.obtainMessage(
5304 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5305 locales.get(bestLocaleIndex));
5306 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307 }
5308
Yunfan Chen75157d72018-07-27 14:47:21 +09005309 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005310
5311 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005312 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005313
5314 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5315 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005316 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005317
5318 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005319 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005320
5321 AttributeCache ac = AttributeCache.instance();
5322 if (ac != null) {
5323 ac.updateConfiguration(mTempConfig);
5324 }
5325
5326 // Make sure all resources in our process are updated right now, so that anyone who is going
5327 // to retrieve resource values after we return will be sure to get the new ones. This is
5328 // especially important during boot, where the first config change needs to guarantee all
5329 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005330 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005331
5332 // We need another copy of global config because we're scheduling some calls instead of
5333 // running them in place. We need to be sure that object we send will be handled unchanged.
5334 final Configuration configCopy = new Configuration(mTempConfig);
5335 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005336 final Message msg = PooledLambda.obtainMessage(
5337 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5338 this, userId, configCopy);
5339 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005340 }
5341
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005342 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5343 for (int i = pidMap.size() - 1; i >= 0; i--) {
5344 final int pid = pidMap.keyAt(i);
5345 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005346 if (DEBUG_CONFIGURATION) {
5347 Slog.v(TAG_CONFIGURATION, "Update process config of "
5348 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005349 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005350 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351 }
5352
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005353 final Message msg = PooledLambda.obtainMessage(
5354 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5355 mAmInternal, changes, initLocale);
5356 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005357
5358 // Override configuration of the default display duplicates global config, so we need to
5359 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005360 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005361 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005362
5363 return changes;
5364 }
5365
Riddle Hsua0022cd2019-09-09 21:12:41 +08005366 /** @see WindowSurfacePlacer#deferLayout */
5367 void deferWindowLayout() {
5368 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5369 // Reset the reasons at the first entrance because we only care about the changes in the
5370 // deferred scope.
5371 mLayoutReasons = 0;
5372 }
5373
5374 mWindowManager.mWindowPlacerLocked.deferLayout();
5375 }
5376
5377 /** @see WindowSurfacePlacer#continueLayout */
5378 void continueWindowLayout() {
5379 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5380 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5381 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5382 }
5383 }
5384
5385 /**
5386 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5387 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5388 * defer count is gone.
5389 */
5390 void addWindowLayoutReasons(@LayoutReason int reasons) {
5391 mLayoutReasons |= reasons;
5392 }
5393
Wale Ogunwalef6733932018-06-27 05:14:34 -07005394 private void updateEventDispatchingLocked(boolean booted) {
5395 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5396 }
5397
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005398 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5399 final ContentResolver resolver = mContext.getContentResolver();
5400 Settings.System.putConfigurationForUser(resolver, config, userId);
5401 }
5402
5403 private void sendLocaleToMountDaemonMsg(Locale l) {
5404 try {
5405 IBinder service = ServiceManager.getService("mount");
5406 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5407 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5408 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5409 } catch (RemoteException e) {
5410 Log.e(TAG, "Error storing locale for decryption UI", e);
5411 }
5412 }
5413
Alison Cichowlas3e340502018-08-07 17:15:01 -04005414 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5415 mStartActivitySources.remove(permissionToken);
5416 mExpiredStartAsCallerTokens.add(permissionToken);
5417 }
5418
5419 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5420 mExpiredStartAsCallerTokens.remove(permissionToken);
5421 }
5422
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005423 boolean isActivityStartsLoggingEnabled() {
5424 return mAmInternal.isActivityStartsLoggingEnabled();
5425 }
5426
Michal Karpinski8596ded2018-11-14 14:43:48 +00005427 boolean isBackgroundActivityStartsEnabled() {
5428 return mAmInternal.isBackgroundActivityStartsEnabled();
5429 }
5430
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005432 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005433 mWindowManager.enableScreenAfterBoot();
5434
5435 synchronized (mGlobalLock) {
5436 updateEventDispatchingLocked(booted);
5437 }
5438 }
5439
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005440 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5441 if (r == null || !r.hasProcess()) {
5442 return KEY_DISPATCHING_TIMEOUT_MS;
5443 }
5444 return getInputDispatchingTimeoutLocked(r.app);
5445 }
5446
5447 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005448 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005449 }
5450
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 /**
5452 * Decide based on the configuration whether we should show the ANR,
5453 * crash, etc dialogs. The idea is that if there is no affordance to
5454 * press the on-screen buttons, or the user experience would be more
5455 * greatly impacted than the crash itself, we shouldn't show the dialog.
5456 *
5457 * A thought: SystemUI might also want to get told about this, the Power
5458 * dialog / global actions also might want different behaviors.
5459 */
5460 private void updateShouldShowDialogsLocked(Configuration config) {
5461 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5462 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5463 && config.navigation == Configuration.NAVIGATION_NONAV);
5464 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5465 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5466 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5467 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5468 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5469 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5470 HIDE_ERROR_DIALOGS, 0) != 0;
5471 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5472 }
5473
5474 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5475 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5476 FONT_SCALE, 1.0f, userId);
5477
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005478 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479 if (getGlobalConfiguration().fontScale == scaleFactor) {
5480 return;
5481 }
5482
5483 final Configuration configuration
5484 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5485 configuration.fontScale = scaleFactor;
5486 updatePersistentConfiguration(configuration, userId);
5487 }
5488 }
5489
5490 // Actually is sleeping or shutting down or whatever else in the future
5491 // is an inactive state.
5492 boolean isSleepingOrShuttingDownLocked() {
5493 return isSleepingLocked() || mShuttingDown;
5494 }
5495
5496 boolean isSleepingLocked() {
5497 return mSleeping;
5498 }
5499
Riddle Hsu16567132018-08-16 21:37:47 +08005500 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005501 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005502 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005503 if (task.isActivityTypeStandard()) {
5504 if (mCurAppTimeTracker != r.appTimeTracker) {
5505 // We are switching app tracking. Complete the current one.
5506 if (mCurAppTimeTracker != null) {
5507 mCurAppTimeTracker.stop();
5508 mH.obtainMessage(
5509 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005510 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 mCurAppTimeTracker = null;
5512 }
5513 if (r.appTimeTracker != null) {
5514 mCurAppTimeTracker = r.appTimeTracker;
5515 startTimeTrackingFocusedActivityLocked();
5516 }
5517 } else {
5518 startTimeTrackingFocusedActivityLocked();
5519 }
5520 } else {
5521 r.appTimeTracker = null;
5522 }
5523 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5524 // TODO: Probably not, because we don't want to resume voice on switching
5525 // back to this activity
5526 if (task.voiceInteractor != null) {
5527 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5528 } else {
5529 finishRunningVoiceLocked();
5530
5531 if (mLastResumedActivity != null) {
5532 final IVoiceInteractionSession session;
5533
Louis Changcdec0802019-11-11 11:45:07 +08005534 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005535 if (lastResumedActivityTask != null
5536 && lastResumedActivityTask.voiceSession != null) {
5537 session = lastResumedActivityTask.voiceSession;
5538 } else {
5539 session = mLastResumedActivity.voiceSession;
5540 }
5541
5542 if (session != null) {
5543 // We had been in a voice interaction session, but now focused has
5544 // move to something different. Just finish the session, we can't
5545 // return to it and retain the proper state and synchronization with
5546 // the voice interaction service.
5547 finishVoiceTask(session);
5548 }
5549 }
5550 }
5551
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005552 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5553 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005555 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5556
Wale Ogunwalef6733932018-06-27 05:14:34 -07005557 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
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005562 if (prevTask == null || task != prevTask) {
5563 if (prevTask != null) {
5564 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5565 }
5566 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5567 }
5568
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569 applyUpdateLockStateLocked(r);
5570 applyUpdateVrModeLocked(r);
5571
Jeff Changd136e772019-11-05 20:33:52 +08005572 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005573 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005574 r == null ? "NULL" : r.shortComponentName,
5575 reason);
5576 }
5577
5578 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5579 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005580 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005581 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005582 updateSleepIfNeededLocked();
5583 return token;
5584 }
5585 }
5586
5587 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005588 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589 final boolean wasSleeping = mSleeping;
5590 boolean updateOomAdj = false;
5591
5592 if (!shouldSleep) {
5593 // If wasSleeping is true, we need to wake up activity manager state from when
5594 // we started sleeping. In either case, we need to apply the sleep tokens, which
5595 // will wake up stacks or put them to sleep as appropriate.
5596 if (wasSleeping) {
5597 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005598 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5599 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600 startTimeTrackingFocusedActivityLocked();
5601 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005602 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5604 }
Louis Chang149d5c82019-12-30 09:47:39 +08005605 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 if (wasSleeping) {
5607 updateOomAdj = true;
5608 }
5609 } else if (!mSleeping && shouldSleep) {
5610 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005611 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5612 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005613 if (mCurAppTimeTracker != null) {
5614 mCurAppTimeTracker.stop();
5615 }
5616 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005617 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005618 mStackSupervisor.goingToSleepLocked();
5619 updateResumedAppTrace(null /* resumed */);
5620 updateOomAdj = true;
5621 }
5622 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005623 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005624 }
5625 }
5626
5627 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005628 mH.removeCallbacks(mUpdateOomAdjRunnable);
5629 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005630 }
5631
Wale Ogunwale53783742018-09-16 10:21:51 -07005632 void updateCpuStats() {
5633 mH.post(mAmInternal::updateCpuStats);
5634 }
5635
Hui Yu03d12402018-12-06 18:00:37 -08005636 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5637 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005638 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5639 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005640 mH.sendMessage(m);
5641 }
5642
Hui Yu03d12402018-12-06 18:00:37 -08005643 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005644 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005645 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005646 if (task != null) {
5647 final ActivityRecord rootActivity = task.getRootActivity();
5648 if (rootActivity != null) {
5649 taskRoot = rootActivity.mActivityComponent;
5650 }
5651 }
5652
Hui Yu03d12402018-12-06 18:00:37 -08005653 final Message m = PooledLambda.obtainMessage(
5654 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005655 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005656 mH.sendMessage(m);
5657 }
5658
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005659 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5660 String hostingType) {
5661 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005662 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5663 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005664 + activity.processName);
5665 }
5666 // Post message to start process to avoid possible deadlock of calling into AMS with the
5667 // ATMS lock held.
5668 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5669 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5670 isTop, hostingType, activity.intent.getComponent());
5671 mH.sendMessage(m);
5672 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005673 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005674 }
5675 }
5676
Wale Ogunwale53783742018-09-16 10:21:51 -07005677 void setBooting(boolean booting) {
5678 mAmInternal.setBooting(booting);
5679 }
5680
5681 boolean isBooting() {
5682 return mAmInternal.isBooting();
5683 }
5684
5685 void setBooted(boolean booted) {
5686 mAmInternal.setBooted(booted);
5687 }
5688
5689 boolean isBooted() {
5690 return mAmInternal.isBooted();
5691 }
5692
5693 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5694 mH.post(() -> {
5695 if (finishBooting) {
5696 mAmInternal.finishBooting();
5697 }
5698 if (enableScreen) {
5699 mInternal.enableScreenAfterBoot(isBooted());
5700 }
5701 });
5702 }
5703
5704 void setHeavyWeightProcess(ActivityRecord root) {
5705 mHeavyWeightProcess = root.app;
5706 final Message m = PooledLambda.obtainMessage(
5707 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005708 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005709 mH.sendMessage(m);
5710 }
5711
5712 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5713 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5714 return;
5715 }
5716
5717 mHeavyWeightProcess = null;
5718 final Message m = PooledLambda.obtainMessage(
5719 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5720 proc.mUserId);
5721 mH.sendMessage(m);
5722 }
5723
5724 private void cancelHeavyWeightProcessNotification(int userId) {
5725 final INotificationManager inm = NotificationManager.getService();
5726 if (inm == null) {
5727 return;
5728 }
5729 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005730 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005731 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5732 } catch (RuntimeException e) {
5733 Slog.w(TAG, "Error canceling notification for service", e);
5734 } catch (RemoteException e) {
5735 }
5736
5737 }
5738
5739 private void postHeavyWeightProcessNotification(
5740 WindowProcessController proc, Intent intent, int userId) {
5741 if (proc == null) {
5742 return;
5743 }
5744
5745 final INotificationManager inm = NotificationManager.getService();
5746 if (inm == null) {
5747 return;
5748 }
5749
5750 try {
5751 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5752 String text = mContext.getString(R.string.heavy_weight_notification,
5753 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5754 Notification notification =
5755 new Notification.Builder(context,
5756 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5757 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5758 .setWhen(0)
5759 .setOngoing(true)
5760 .setTicker(text)
5761 .setColor(mContext.getColor(
5762 com.android.internal.R.color.system_notification_accent_color))
5763 .setContentTitle(text)
5764 .setContentText(
5765 mContext.getText(R.string.heavy_weight_notification_detail))
5766 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5767 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5768 new UserHandle(userId)))
5769 .build();
5770 try {
5771 inm.enqueueNotificationWithTag("android", "android", null,
5772 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5773 } catch (RuntimeException e) {
5774 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5775 } catch (RemoteException e) {
5776 }
5777 } catch (PackageManager.NameNotFoundException e) {
5778 Slog.w(TAG, "Unable to create context for heavy notification", e);
5779 }
5780
5781 }
5782
Philip P. Moltmannee295092020-02-10 08:46:26 -08005783 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5784 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5785 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005786
5787 ActivityRecord activity = null;
5788 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5789 activity = ActivityRecord.isInStackLocked(token);
5790 if (activity == null) {
5791 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5792 return null;
5793 }
5794 if (activity.finishing) {
5795 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5796 return null;
5797 }
5798 }
5799
5800 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005801 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5802 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005803 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5804 if (noCreate) {
5805 return rec;
5806 }
5807 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5808 if (activity.pendingResults == null) {
5809 activity.pendingResults = new HashSet<>();
5810 }
5811 activity.pendingResults.add(rec.ref);
5812 }
5813 return rec;
5814 }
5815
Andrii Kulian52d255c2018-07-13 11:32:19 -07005816 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005817 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005818 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005819 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5820 mCurAppTimeTracker.start(resumedActivity.packageName);
5821 }
5822 }
5823
5824 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5825 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005826 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005827 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5828 }
5829 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005830 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005831 constructResumedTraceName(resumed.packageName), 0);
5832 }
5833 mTracedResumedActivity = resumed;
5834 }
5835
5836 private String constructResumedTraceName(String packageName) {
5837 return "focused app: " + packageName;
5838 }
5839
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005840 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005841 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005842 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005843 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005844 // mainStack is null during startup.
5845 if (mainStack != null) {
5846 if (changes != 0 && starting == null) {
5847 // If the configuration changed, and the caller is not already
5848 // in the process of starting an activity, then find the top
5849 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005850 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005851 }
5852
5853 if (starting != null) {
5854 kept = starting.ensureActivityConfiguration(changes,
5855 false /* preserveWindow */);
5856 // And we need to make sure at this point that all other activities
5857 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005858 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005859 !PRESERVE_WINDOWS);
5860 }
5861 }
5862
5863 return kept;
5864 }
5865
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005866 void scheduleAppGcsLocked() {
5867 mH.post(() -> mAmInternal.scheduleAppGcs());
5868 }
5869
Wale Ogunwale53783742018-09-16 10:21:51 -07005870 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5871 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5872 }
5873
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005874 /**
5875 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5876 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5877 * on demand.
5878 */
5879 IPackageManager getPackageManager() {
5880 return AppGlobals.getPackageManager();
5881 }
5882
5883 PackageManagerInternal getPackageManagerInternalLocked() {
5884 if (mPmInternal == null) {
5885 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5886 }
5887 return mPmInternal;
5888 }
5889
Hai Zhangf4da9be2019-05-01 13:46:06 +08005890 PermissionPolicyInternal getPermissionPolicyInternal() {
5891 if (mPermissionPolicyInternal == null) {
5892 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5893 }
5894 return mPermissionPolicyInternal;
5895 }
5896
Wale Ogunwale008163e2018-07-23 23:11:08 -07005897 AppWarnings getAppWarningsLocked() {
5898 return mAppWarnings;
5899 }
5900
Wale Ogunwale214f3482018-10-04 11:00:47 -07005901 Intent getHomeIntent() {
5902 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5903 intent.setComponent(mTopComponent);
5904 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5905 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5906 intent.addCategory(Intent.CATEGORY_HOME);
5907 }
5908 return intent;
5909 }
5910
Chilun2ef71f72018-11-16 17:57:15 +08005911 /**
5912 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5913 * activities.
5914 *
5915 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5916 * component defined in config_secondaryHomeComponent.
5917 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5918 */
5919 Intent getSecondaryHomeIntent(String preferredPackage) {
5920 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005921 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5922 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5923 if (preferredPackage == null || useSystemProvidedLauncher) {
5924 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005925 final String secondaryHomeComponent = mContext.getResources().getString(
5926 com.android.internal.R.string.config_secondaryHomeComponent);
5927 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5928 } else {
5929 intent.setPackage(preferredPackage);
5930 }
5931 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5932 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5933 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5934 }
5935 return intent;
5936 }
5937
Wale Ogunwale214f3482018-10-04 11:00:47 -07005938 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5939 if (info == null) return null;
5940 ApplicationInfo newInfo = new ApplicationInfo(info);
5941 newInfo.initForUser(userId);
5942 return newInfo;
5943 }
5944
Wale Ogunwale9c103022018-10-18 07:44:54 -07005945 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005946 if (uid == SYSTEM_UID) {
5947 // The system gets to run in any process. If there are multiple processes with the same
5948 // uid, just pick the first (this should never happen).
5949 final SparseArray<WindowProcessController> procs =
5950 mProcessNames.getMap().get(processName);
5951 if (procs == null) return null;
5952 final int procCount = procs.size();
5953 for (int i = 0; i < procCount; i++) {
5954 final int procUid = procs.keyAt(i);
5955 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5956 // Don't use an app process or different user process for system component.
5957 continue;
5958 }
5959 return procs.valueAt(i);
5960 }
5961 }
5962
5963 return mProcessNames.get(processName, uid);
5964 }
5965
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005966 WindowProcessController getProcessController(IApplicationThread thread) {
5967 if (thread == null) {
5968 return null;
5969 }
5970
5971 final IBinder threadBinder = thread.asBinder();
5972 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5973 for (int i = pmap.size()-1; i >= 0; i--) {
5974 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5975 for (int j = procs.size() - 1; j >= 0; j--) {
5976 final WindowProcessController proc = procs.valueAt(j);
5977 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5978 return proc;
5979 }
5980 }
5981 }
5982
5983 return null;
5984 }
5985
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005986 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005987 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005988 if (proc == null) return null;
5989 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5990 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005991 }
5992 return null;
5993 }
5994
Riddle Hsua0536432019-02-16 00:38:59 +08005995 int getUidState(int uid) {
5996 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005997 }
5998
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005999 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006000 // A uid is considered to be foreground if it has a visible non-toast window.
6001 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006002 }
6003
Ricky Wai96f5c352019-04-10 18:40:17 +01006004 boolean isDeviceOwner(int uid) {
6005 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006006 }
6007
Ricky Wai96f5c352019-04-10 18:40:17 +01006008 void setDeviceOwnerUid(int uid) {
6009 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006010 }
6011
Wale Ogunwale9de19442018-10-18 19:05:03 -07006012 /**
6013 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6014 * the whitelist
6015 */
6016 String getPendingTempWhitelistTagForUidLocked(int uid) {
6017 return mPendingTempWhitelist.get(uid);
6018 }
6019
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006020 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6021 if (true || Build.IS_USER) {
6022 return;
6023 }
6024
6025 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6026 StrictMode.allowThreadDiskWrites();
6027 try {
6028 File tracesDir = new File("/data/anr");
6029 File tracesFile = null;
6030 try {
6031 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6032
6033 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006034 String timeString =
6035 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6036 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006037 sb.append(": ");
6038 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6039 sb.append(" since ");
6040 sb.append(msg);
6041 FileOutputStream fos = new FileOutputStream(tracesFile);
6042 fos.write(sb.toString().getBytes());
6043 if (app == null) {
6044 fos.write("\n*** No application process!".getBytes());
6045 }
6046 fos.close();
6047 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6048 } catch (IOException e) {
6049 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6050 return;
6051 }
6052
6053 if (app != null && app.getPid() > 0) {
6054 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6055 firstPids.add(app.getPid());
6056 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6057 }
6058
6059 File lastTracesFile = null;
6060 File curTracesFile = null;
6061 for (int i=9; i>=0; i--) {
6062 String name = String.format(Locale.US, "slow%02d.txt", i);
6063 curTracesFile = new File(tracesDir, name);
6064 if (curTracesFile.exists()) {
6065 if (lastTracesFile != null) {
6066 curTracesFile.renameTo(lastTracesFile);
6067 } else {
6068 curTracesFile.delete();
6069 }
6070 }
6071 lastTracesFile = curTracesFile;
6072 }
6073 tracesFile.renameTo(curTracesFile);
6074 } finally {
6075 StrictMode.setThreadPolicy(oldPolicy);
6076 }
6077 }
6078
Michal Karpinskida34cd42019-04-02 19:46:52 +01006079 boolean isAssociatedCompanionApp(int userId, int uid) {
6080 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6081 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006082 return false;
6083 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006084 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006085 }
6086
Issei Suzuki734bc942019-06-05 13:59:52 +02006087 void notifySingleTaskDisplayEmpty(int displayId) {
6088 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6089 }
6090
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006091 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006092 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006093
6094
Wale Ogunwale98875612018-10-12 07:53:02 -07006095 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6096 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006097
Riddle Hsud93a6c42018-11-29 21:50:06 +08006098 H(Looper looper) {
6099 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006100 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006101
6102 @Override
6103 public void handleMessage(Message msg) {
6104 switch (msg.what) {
6105 case REPORT_TIME_TRACKER_MSG: {
6106 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6107 tracker.deliverResult(mContext);
6108 } break;
6109 }
6110 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006111 }
6112
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006113 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006114 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006115
6116 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006117 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006118 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006119
6120 @Override
6121 public void handleMessage(Message msg) {
6122 switch (msg.what) {
6123 case DISMISS_DIALOG_UI_MSG: {
6124 final Dialog d = (Dialog) msg.obj;
6125 d.dismiss();
6126 break;
6127 }
6128 }
6129 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006130 }
6131
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006132 final class LocalService extends ActivityTaskManagerInternal {
6133 @Override
6134 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006135 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006136 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006137 }
6138
6139 @Override
6140 public ComponentName getHomeActivityForUser(int userId) {
6141 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006142 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006143 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006144 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 }
6146 }
6147
6148 @Override
6149 public void onLocalVoiceInteractionStarted(IBinder activity,
6150 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6151 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006152 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 }
6154 }
6155
6156 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006157 public void notifySingleTaskDisplayDrawn(int displayId) {
6158 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6159 }
6160
6161 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 public void notifyAppTransitionFinished() {
6163 synchronized (mGlobalLock) {
6164 mStackSupervisor.notifyAppTransitionDone();
6165 }
6166 }
6167
6168 @Override
6169 public void notifyAppTransitionCancelled() {
6170 synchronized (mGlobalLock) {
6171 mStackSupervisor.notifyAppTransitionDone();
6172 }
6173 }
6174
6175 @Override
6176 public List<IBinder> getTopVisibleActivities() {
6177 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006178 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 }
6180 }
6181
6182 @Override
6183 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6184 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006185 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 }
6187 }
6188
6189 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006190 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6191 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006192 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193 final String[] resolvedTypes = new String[intents.length];
6194
6195 // UID of the package on user userId.
6196 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6197 // packageUid may not be initialized.
6198 int packageUid = 0;
6199 final long ident = Binder.clearCallingIdentity();
6200
6201 try {
6202 for (int i = 0; i < intents.length; i++) {
6203 resolvedTypes[i] =
6204 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6205 }
6206
6207 packageUid = AppGlobals.getPackageManager().getPackageUid(
6208 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6209 } catch (RemoteException e) {
6210 // Shouldn't happen.
6211 } finally {
6212 Binder.restoreCallingIdentity(ident);
6213 }
6214
Riddle Hsu591bf612019-02-14 17:55:31 +08006215 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006216 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006217 intents, resolvedTypes, null /* resultTo */,
6218 SafeActivityOptions.fromBundle(bOptions), userId,
6219 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6220 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006221 }
6222
6223 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006224 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006225 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6226 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6227 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006228 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006229 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006230 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006231 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006232 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6233 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006234 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006235 }
6236 }
6237
6238 @Override
6239 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006240 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6241 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6242 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6243 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006244 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006245 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006246 synchronized (mGlobalLock) {
6247 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006248 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6249 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6250 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006251 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006252 }
6253 }
6254
6255 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006256 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006257 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6258 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006260 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006261 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006262 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 false /*validateIncomingUser*/);
6264 }
6265
6266 @Override
lumark588a3e82018-07-20 18:53:54 +08006267 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006268 synchronized (mGlobalLock) {
6269
6270 // We might change the visibilities here, so prepare an empty app transition which
6271 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006272 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006273 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006274 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006275 return;
6276 }
Louis Chang677921f2019-12-06 16:44:24 +08006277 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006278 final boolean wasTransitionSet =
6279 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006280 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006281 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
Louis Chang149d5c82019-12-30 09:47:39 +08006283 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006284
6285 // If there was a transition set already we don't want to interfere with it as we
6286 // might be starting it too early.
6287 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006288 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290 }
6291 if (callback != null) {
6292 callback.run();
6293 }
6294 }
6295
6296 @Override
6297 public void notifyKeyguardTrustedChanged() {
6298 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006299 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006300 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 }
6302 }
6303 }
6304
6305 /**
6306 * Called after virtual display Id is updated by
6307 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6308 * {@param vrVr2dDisplayId}.
6309 */
6310 @Override
6311 public void setVr2dDisplayId(int vr2dDisplayId) {
6312 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6313 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006314 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
6316 }
6317
6318 @Override
6319 public void setFocusedActivity(IBinder token) {
6320 synchronized (mGlobalLock) {
6321 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6322 if (r == null) {
6323 throw new IllegalArgumentException(
6324 "setFocusedActivity: No activity record matching token=" + token);
6325 }
Louis Chang19443452018-10-09 12:10:21 +08006326 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006327 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006328 }
6329 }
6330 }
6331
6332 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006333 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006334 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006335 }
6336
6337 @Override
6338 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006339 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006340 }
6341
6342 @Override
6343 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006344 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006345 }
6346
6347 @Override
6348 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6349 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6350 }
6351
6352 @Override
6353 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006354 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006355 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006356
6357 @Override
6358 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6359 synchronized (mGlobalLock) {
6360 mActiveVoiceInteractionServiceComponent = component;
6361 }
6362 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006363
6364 @Override
6365 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6366 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6367 return;
6368 }
6369 synchronized (mGlobalLock) {
6370 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6371 if (types == null) {
6372 if (uid < 0) {
6373 return;
6374 }
6375 types = new ArrayMap<>();
6376 mAllowAppSwitchUids.put(userId, types);
6377 }
6378 if (uid < 0) {
6379 types.remove(type);
6380 } else {
6381 types.put(type, uid);
6382 }
6383 }
6384 }
6385
6386 @Override
6387 public void onUserStopped(int userId) {
6388 synchronized (mGlobalLock) {
6389 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6390 mAllowAppSwitchUids.remove(userId);
6391 }
6392 }
6393
6394 @Override
6395 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6396 synchronized (mGlobalLock) {
6397 return ActivityTaskManagerService.this.isGetTasksAllowed(
6398 caller, callingPid, callingUid);
6399 }
6400 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006401
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 onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006405 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006406 mProcessNames.put(proc.mName, proc.mUid, proc);
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 onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006413 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006414 mProcessNames.remove(name, uid);
6415 }
6416 }
6417
Riddle Hsua0536432019-02-16 00:38:59 +08006418 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006419 @Override
6420 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006421 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006422 if (proc == mHomeProcess) {
6423 mHomeProcess = null;
6424 }
6425 if (proc == mPreviousProcess) {
6426 mPreviousProcess = null;
6427 }
6428 }
6429 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006430
Riddle Hsua0536432019-02-16 00:38:59 +08006431 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006432 @Override
6433 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006434 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006435 return mTopProcessState;
6436 }
6437 }
6438
Riddle Hsua0536432019-02-16 00:38:59 +08006439 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006440 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006442 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006443 return proc == mHeavyWeightProcess;
6444 }
6445 }
6446
Riddle Hsua0536432019-02-16 00:38:59 +08006447 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006448 @Override
6449 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006450 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006451 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6452 }
6453 }
6454
6455 @Override
6456 public void finishHeavyWeightApp() {
6457 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006458 if (mHeavyWeightProcess != null) {
6459 mHeavyWeightProcess.finishActivities();
6460 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006461 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6462 mHeavyWeightProcess);
6463 }
6464 }
6465
Riddle Hsua0536432019-02-16 00:38:59 +08006466 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006467 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006468 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006469 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006470 return isSleepingLocked();
6471 }
6472 }
6473
6474 @Override
6475 public boolean isShuttingDown() {
6476 synchronized (mGlobalLock) {
6477 return mShuttingDown;
6478 }
6479 }
6480
6481 @Override
6482 public boolean shuttingDown(boolean booted, int timeout) {
6483 synchronized (mGlobalLock) {
6484 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006485 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006486 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006487 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006488 return mStackSupervisor.shutdownLocked(timeout);
6489 }
6490 }
6491
6492 @Override
6493 public void enableScreenAfterBoot(boolean booted) {
6494 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006495 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006496 mWindowManager.enableScreenAfterBoot();
6497 updateEventDispatchingLocked(booted);
6498 }
6499 }
6500
6501 @Override
6502 public boolean showStrictModeViolationDialog() {
6503 synchronized (mGlobalLock) {
6504 return mShowDialogs && !mSleeping && !mShuttingDown;
6505 }
6506 }
6507
6508 @Override
6509 public void showSystemReadyErrorDialogsIfNeeded() {
6510 synchronized (mGlobalLock) {
6511 try {
6512 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6513 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6514 + " data partition or your device will be unstable.");
6515 mUiHandler.post(() -> {
6516 if (mShowDialogs) {
6517 AlertDialog d = new BaseErrorDialog(mUiContext);
6518 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6519 d.setCancelable(false);
6520 d.setTitle(mUiContext.getText(R.string.android_system_label));
6521 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6522 d.setButton(DialogInterface.BUTTON_POSITIVE,
6523 mUiContext.getText(R.string.ok),
6524 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6525 d.show();
6526 }
6527 });
6528 }
6529 } catch (RemoteException e) {
6530 }
6531
6532 if (!Build.isBuildConsistent()) {
6533 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6534 mUiHandler.post(() -> {
6535 if (mShowDialogs) {
6536 AlertDialog d = new BaseErrorDialog(mUiContext);
6537 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6538 d.setCancelable(false);
6539 d.setTitle(mUiContext.getText(R.string.android_system_label));
6540 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6541 d.setButton(DialogInterface.BUTTON_POSITIVE,
6542 mUiContext.getText(R.string.ok),
6543 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6544 d.show();
6545 }
6546 });
6547 }
6548 }
6549 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006550
6551 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006552 public void onProcessMapped(int pid, WindowProcessController proc) {
6553 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006554 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006555 }
6556 }
6557
6558 @Override
6559 public void onProcessUnMapped(int pid) {
6560 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006561 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006562 }
6563 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006564
6565 @Override
6566 public void onPackageDataCleared(String name) {
6567 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006568 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006569 mAppWarnings.onPackageDataCleared(name);
6570 }
6571 }
6572
6573 @Override
6574 public void onPackageUninstalled(String name) {
6575 synchronized (mGlobalLock) {
6576 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006577 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006578 }
6579 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006580
6581 @Override
6582 public void onPackageAdded(String name, boolean replacing) {
6583 synchronized (mGlobalLock) {
6584 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6585 }
6586 }
6587
6588 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006589 public void onPackageReplaced(ApplicationInfo aInfo) {
6590 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006591 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006592 }
6593 }
6594
6595 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006596 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6597 synchronized (mGlobalLock) {
6598 return compatibilityInfoForPackageLocked(ai);
6599 }
6600 }
6601
Yunfan Chen75157d72018-07-27 14:47:21 +09006602 /**
6603 * Set the corresponding display information for the process global configuration. To be
6604 * called when we need to show IME on a different display.
6605 *
6606 * @param pid The process id associated with the IME window.
6607 * @param displayId The ID of the display showing the IME.
6608 */
6609 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006610 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006611 // Don't update process-level configuration for Multi-Client IME process since other
6612 // IMEs on other displays will also receive this configuration change due to IME
6613 // services use the same application config/context.
6614 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006615
Yunfan Chen75157d72018-07-27 14:47:21 +09006616 if (pid == MY_PID || pid < 0) {
6617 if (DEBUG_CONFIGURATION) {
6618 Slog.w(TAG,
6619 "Trying to update display configuration for system/invalid process.");
6620 }
6621 return;
6622 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006623 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006624 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006625 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006626 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006627 // Call might come when display is not yet added or has been removed.
6628 if (DEBUG_CONFIGURATION) {
6629 Slog.w(TAG, "Trying to update display configuration for non-existing "
6630 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006631 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006632 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006633 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006634 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006635 if (process == null) {
6636 if (DEBUG_CONFIGURATION) {
6637 Slog.w(TAG, "Trying to update display configuration for invalid "
6638 + "process, pid=" + pid);
6639 }
6640 return;
6641 }
lumarkddc77fb2019-06-27 22:22:23 +08006642 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006643 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006644 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006645 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006646
6647 @Override
6648 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006649 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006650 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006651 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006652 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006653 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006654 }
6655 }
6656 }
6657
6658 @Override
6659 public void clearPendingResultForActivity(IBinder activityToken,
6660 WeakReference<PendingIntentRecord> pir) {
6661 synchronized (mGlobalLock) {
6662 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6663 if (r != null && r.pendingResults != null) {
6664 r.pendingResults.remove(pir);
6665 }
6666 }
6667 }
6668
6669 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006670 public ActivityTokens getTopActivityForTask(int taskId) {
6671 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006672 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006673 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006674 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6675 + " Requested task not found");
6676 return null;
6677 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006678 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006679 if (activity == null) {
6680 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6681 + " Requested activity not found");
6682 return null;
6683 }
6684 if (!activity.attachedToProcess()) {
6685 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6686 + activity);
6687 return null;
6688 }
6689 return new ActivityTokens(activity.appToken, activity.assistToken,
6690 activity.app.getThread());
6691 }
6692 }
6693
6694 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006695 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006696 @Nullable String featureId, int callingUid, int userId, IBinder token,
6697 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6698 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006699 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006700 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6701 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006702 }
6703 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006704
6705 @Override
6706 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6707 synchronized (mGlobalLock) {
6708 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6709 if (r == null) {
6710 return null;
6711 }
6712 if (r.mServiceConnectionsHolder == null) {
6713 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6714 ActivityTaskManagerService.this, r);
6715 }
6716
6717 return r.mServiceConnectionsHolder;
6718 }
6719 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006720
6721 @Override
6722 public Intent getHomeIntent() {
6723 synchronized (mGlobalLock) {
6724 return ActivityTaskManagerService.this.getHomeIntent();
6725 }
6726 }
6727
6728 @Override
6729 public boolean startHomeActivity(int userId, String reason) {
6730 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006731 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006732 }
6733 }
6734
6735 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006736 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006737 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006738 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006739 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006740 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006741 }
Chilun8b1f1be2019-03-13 17:14:36 +08006742 }
6743
6744 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006745 public boolean startHomeOnAllDisplays(int userId, String reason) {
6746 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006747 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006748 }
6749 }
6750
Riddle Hsua0536432019-02-16 00:38:59 +08006751 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006752 @Override
6753 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006754 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006755 if (mFactoryTest == FACTORY_TEST_OFF) {
6756 return false;
6757 }
6758 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6759 && wpc.mName.equals(mTopComponent.getPackageName())) {
6760 return true;
6761 }
6762 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6763 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6764 }
6765 }
6766
6767 @Override
6768 public void updateTopComponentForFactoryTest() {
6769 synchronized (mGlobalLock) {
6770 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6771 return;
6772 }
6773 final ResolveInfo ri = mContext.getPackageManager()
6774 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6775 final CharSequence errorMsg;
6776 if (ri != null) {
6777 final ActivityInfo ai = ri.activityInfo;
6778 final ApplicationInfo app = ai.applicationInfo;
6779 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6780 mTopAction = Intent.ACTION_FACTORY_TEST;
6781 mTopData = null;
6782 mTopComponent = new ComponentName(app.packageName, ai.name);
6783 errorMsg = null;
6784 } else {
6785 errorMsg = mContext.getResources().getText(
6786 com.android.internal.R.string.factorytest_not_system);
6787 }
6788 } else {
6789 errorMsg = mContext.getResources().getText(
6790 com.android.internal.R.string.factorytest_no_action);
6791 }
6792 if (errorMsg == null) {
6793 return;
6794 }
6795
6796 mTopAction = null;
6797 mTopData = null;
6798 mTopComponent = null;
6799 mUiHandler.post(() -> {
6800 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6801 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006802 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006803 });
6804 }
6805 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806
Riddle Hsua0536432019-02-16 00:38:59 +08006807 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006808 @Override
6809 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6810 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006811 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006813 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814
6815 wpc.clearRecentTasks();
6816 wpc.clearActivities();
6817
6818 if (wpc.isInstrumenting()) {
6819 finishInstrumentationCallback.run();
6820 }
6821
Jorim Jaggid0752812018-10-16 16:07:20 +02006822 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006823 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006824 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006825 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006826 // If there was nothing to resume, and we are not already restarting
6827 // this process, but there is a visible activity that is hosted by the
6828 // process...then make sure all visible activities are running, taking
6829 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006830 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006831 !PRESERVE_WINDOWS);
6832 }
6833 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006834 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836 }
6837 }
6838 }
6839
6840 @Override
6841 public void closeSystemDialogs(String reason) {
6842 enforceNotIsolatedCaller("closeSystemDialogs");
6843
6844 final int pid = Binder.getCallingPid();
6845 final int uid = Binder.getCallingUid();
6846 final long origId = Binder.clearCallingIdentity();
6847 try {
6848 synchronized (mGlobalLock) {
6849 // Only allow this from foreground processes, so that background
6850 // applications can't abuse it to prevent system UI from being shown.
6851 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006852 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006853 if (!proc.isPerceptible()) {
6854 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6855 + " from background process " + proc);
6856 return;
6857 }
6858 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 mWindowManager.closeSystemDialogs(reason);
6860
Louis Chang149d5c82019-12-30 09:47:39 +08006861 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006863 // Call into AM outside the synchronized block.
6864 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 } finally {
6866 Binder.restoreCallingIdentity(origId);
6867 }
6868 }
6869
6870 @Override
6871 public void cleanupDisabledPackageComponents(
6872 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6873 synchronized (mGlobalLock) {
6874 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006875 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006876 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006877 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006878 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 }
6880
6881 // Clean-up disabled tasks
6882 getRecentTasks().cleanupDisabledPackageTasksLocked(
6883 packageName, disabledClasses, userId);
6884 }
6885 }
6886
6887 @Override
6888 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6889 int userId) {
6890 synchronized (mGlobalLock) {
6891
6892 boolean didSomething =
6893 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006894 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 null, doit, evenPersistent, userId);
6896 return didSomething;
6897 }
6898 }
6899
6900 @Override
6901 public void resumeTopActivities(boolean scheduleIdle) {
6902 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006903 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006905 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 }
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 void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006913 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6915 }
6916 }
6917
Riddle Hsua0536432019-02-16 00:38:59 +08006918 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 @Override
6920 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006921 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006922 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6923 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6924 }
6925 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006926 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006927 } finally {
6928 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6929 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 }
6931 }
6932
6933 @Override
6934 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6935 try {
6936 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6937 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6938 }
6939 } catch (RemoteException ex) {
6940 throw new SecurityException("Fail to check is caller a privileged app", ex);
6941 }
6942
6943 synchronized (mGlobalLock) {
6944 final long ident = Binder.clearCallingIdentity();
6945 try {
6946 if (mAmInternal.shouldConfirmCredentials(userId)) {
6947 if (mKeyguardController.isKeyguardLocked()) {
6948 // Showing launcher to avoid user entering credential twice.
6949 startHomeActivity(currentUserId, "notifyLockedProfile");
6950 }
Louis Chang149d5c82019-12-30 09:47:39 +08006951 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006952 }
6953 } finally {
6954 Binder.restoreCallingIdentity(ident);
6955 }
6956 }
6957 }
6958
6959 @Override
6960 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6961 mAmInternal.enforceCallingPermission(
6962 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6963
6964 synchronized (mGlobalLock) {
6965 final long ident = Binder.clearCallingIdentity();
6966 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006967 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6968 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006969 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006970 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6971 UserHandle.CURRENT);
6972 } finally {
6973 Binder.restoreCallingIdentity(ident);
6974 }
6975 }
6976 }
6977
6978 @Override
6979 public void writeActivitiesToProto(ProtoOutputStream proto) {
6980 synchronized (mGlobalLock) {
6981 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08006982 mRootWindowContainer.dumpDebug(
6983 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006984 }
6985 }
6986
6987 @Override
6988 public void saveANRState(String reason) {
6989 synchronized (mGlobalLock) {
6990 final StringWriter sw = new StringWriter();
6991 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6992 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6993 if (reason != null) {
6994 pw.println(" Reason: " + reason);
6995 }
6996 pw.println();
6997 getActivityStartController().dump(pw, " ", null);
6998 pw.println();
6999 pw.println("-------------------------------------------------------------------------------");
7000 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7001 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7002 "" /* header */);
7003 pw.println();
7004 pw.close();
7005
7006 mLastANRState = sw.toString();
7007 }
7008 }
7009
7010 @Override
7011 public void clearSavedANRState() {
7012 synchronized (mGlobalLock) {
7013 mLastANRState = null;
7014 }
7015 }
7016
7017 @Override
7018 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7019 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7020 synchronized (mGlobalLock) {
7021 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7022 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7023 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7024 dumpLastANRLocked(pw);
7025 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7026 dumpLastANRTracesLocked(pw);
7027 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7028 dumpActivityStarterLocked(pw, dumpPackage);
7029 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7030 dumpActivityContainersLocked(pw);
7031 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7032 if (getRecentTasks() != null) {
7033 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7034 }
7035 }
7036 }
7037 }
7038
7039 @Override
7040 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7041 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7042 int wakefulness) {
7043 synchronized (mGlobalLock) {
7044 if (mHomeProcess != null && (dumpPackage == null
7045 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7046 if (needSep) {
7047 pw.println();
7048 needSep = false;
7049 }
7050 pw.println(" mHomeProcess: " + mHomeProcess);
7051 }
7052 if (mPreviousProcess != null && (dumpPackage == null
7053 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7054 if (needSep) {
7055 pw.println();
7056 needSep = false;
7057 }
7058 pw.println(" mPreviousProcess: " + mPreviousProcess);
7059 }
7060 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7061 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7062 StringBuilder sb = new StringBuilder(128);
7063 sb.append(" mPreviousProcessVisibleTime: ");
7064 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7065 pw.println(sb);
7066 }
7067 if (mHeavyWeightProcess != null && (dumpPackage == null
7068 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7069 if (needSep) {
7070 pw.println();
7071 needSep = false;
7072 }
7073 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7074 }
7075 if (dumpPackage == null) {
7076 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007077 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007078 }
7079 if (dumpAll) {
7080 if (dumpPackage == null) {
7081 pw.println(" mConfigWillChange: "
7082 + getTopDisplayFocusedStack().mConfigWillChange);
7083 }
7084 if (mCompatModePackages.getPackages().size() > 0) {
7085 boolean printed = false;
7086 for (Map.Entry<String, Integer> entry
7087 : mCompatModePackages.getPackages().entrySet()) {
7088 String pkg = entry.getKey();
7089 int mode = entry.getValue();
7090 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7091 continue;
7092 }
7093 if (!printed) {
7094 pw.println(" mScreenCompatPackages:");
7095 printed = true;
7096 }
7097 pw.println(" " + pkg + ": " + mode);
7098 }
7099 }
7100 }
7101
7102 if (dumpPackage == null) {
7103 pw.println(" mWakefulness="
7104 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007105 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 if (mRunningVoice != null) {
7107 pw.println(" mRunningVoice=" + mRunningVoice);
7108 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7109 }
7110 pw.println(" mSleeping=" + mSleeping);
7111 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7112 pw.println(" mVrController=" + mVrController);
7113 }
7114 if (mCurAppTimeTracker != null) {
7115 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7116 }
7117 if (mAllowAppSwitchUids.size() > 0) {
7118 boolean printed = false;
7119 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7120 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7121 for (int j = 0; j < types.size(); j++) {
7122 if (dumpPackage == null ||
7123 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7124 if (needSep) {
7125 pw.println();
7126 needSep = false;
7127 }
7128 if (!printed) {
7129 pw.println(" mAllowAppSwitchUids:");
7130 printed = true;
7131 }
7132 pw.print(" User ");
7133 pw.print(mAllowAppSwitchUids.keyAt(i));
7134 pw.print(": Type ");
7135 pw.print(types.keyAt(j));
7136 pw.print(" = ");
7137 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7138 pw.println();
7139 }
7140 }
7141 }
7142 }
7143 if (dumpPackage == null) {
7144 if (mController != null) {
7145 pw.println(" mController=" + mController
7146 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7147 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007148 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7149 pw.println(" mLaunchingActivityWakeLock="
7150 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 }
7152
7153 return needSep;
7154 }
7155 }
7156
7157 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007158 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7159 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007160 synchronized (mGlobalLock) {
7161 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007162 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007163 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007164 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7165 if (mRunningVoice != null) {
7166 final long vrToken = proto.start(
7167 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7168 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7169 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007170 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007171 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7172 proto.end(vrToken);
7173 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007174 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007175 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007176 if (mController != null) {
7177 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007178 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7179 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7181 proto.end(token);
7182 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007183 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7184 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007185 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007186 }
7187
7188 if (mHomeProcess != null && (dumpPackage == null
7189 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007190 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 }
7192
7193 if (mPreviousProcess != null && (dumpPackage == null
7194 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007195 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007196 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7197 }
7198
7199 if (mHeavyWeightProcess != null && (dumpPackage == null
7200 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007201 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 }
7203
7204 for (Map.Entry<String, Integer> entry
7205 : mCompatModePackages.getPackages().entrySet()) {
7206 String pkg = entry.getKey();
7207 int mode = entry.getValue();
7208 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7209 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7210 proto.write(PACKAGE, pkg);
7211 proto.write(MODE, mode);
7212 proto.end(compatToken);
7213 }
7214 }
7215
7216 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007217 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007218 }
7219
7220 }
7221 }
7222
7223 @Override
7224 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7225 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7226 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007227 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7228 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 }
7230
7231 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007232 public void dumpForOom(PrintWriter pw) {
7233 synchronized (mGlobalLock) {
7234 pw.println(" mHomeProcess: " + mHomeProcess);
7235 pw.println(" mPreviousProcess: " + mPreviousProcess);
7236 if (mHeavyWeightProcess != null) {
7237 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7238 }
7239 }
7240 }
7241
7242 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007243 public boolean canGcNow() {
7244 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007245 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007246 }
7247 }
7248
Riddle Hsua0536432019-02-16 00:38:59 +08007249 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007250 @Override
7251 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007252 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007253 if (mRootWindowContainer == null) {
7254 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007255 // oomadj after AMS created.
7256 return null;
7257 }
Louis Chang149d5c82019-12-30 09:47:39 +08007258 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007259 return top != null ? top.app : null;
7260 }
7261 }
7262
Riddle Hsua0536432019-02-16 00:38:59 +08007263 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007264 @Override
7265 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007266 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007267 if (mRootWindowContainer != null) {
7268 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007269 }
7270 }
7271 }
7272
7273 @Override
7274 public void scheduleDestroyAllActivities(String reason) {
7275 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007276 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007277 }
7278 }
7279
7280 @Override
7281 public void removeUser(int userId) {
7282 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007283 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007284 }
7285 }
7286
7287 @Override
7288 public boolean switchUser(int userId, UserState userState) {
7289 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007290 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292 }
7293
7294 @Override
7295 public void onHandleAppCrash(WindowProcessController wpc) {
7296 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007297 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007298 }
7299 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007300
7301 @Override
7302 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7303 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007304 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007305 }
7306 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007307
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 onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007311 mActiveUids.onUidActive(uid, procState);
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 onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007317 mActiveUids.onUidInactive(uid);
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007323 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007324 }
7325
Riddle Hsua0536432019-02-16 00:38:59 +08007326 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007327 @Override
7328 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007329 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007330 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007331
7332 @Override
7333 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007334 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007335 mPendingTempWhitelist.put(uid, tag);
7336 }
7337 }
7338
7339 @Override
7340 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007341 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007342 mPendingTempWhitelist.remove(uid);
7343 }
7344 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007345
7346 @Override
7347 public boolean handleAppCrashInActivityController(String processName, int pid,
7348 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7349 Runnable killCrashingAppCallback) {
7350 synchronized (mGlobalLock) {
7351 if (mController == null) {
7352 return false;
7353 }
7354
7355 try {
7356 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7357 stackTrace)) {
7358 killCrashingAppCallback.run();
7359 return true;
7360 }
7361 } catch (RemoteException e) {
7362 mController = null;
7363 Watchdog.getInstance().setActivityController(null);
7364 }
7365 return false;
7366 }
7367 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007368
7369 @Override
7370 public void removeRecentTasksByPackageName(String packageName, int userId) {
7371 synchronized (mGlobalLock) {
7372 mRecentTasks.removeTasksByPackageName(packageName, userId);
7373 }
7374 }
7375
7376 @Override
7377 public void cleanupRecentTasksForUser(int userId) {
7378 synchronized (mGlobalLock) {
7379 mRecentTasks.cleanupLocked(userId);
7380 }
7381 }
7382
7383 @Override
7384 public void loadRecentTasksForUser(int userId) {
7385 synchronized (mGlobalLock) {
7386 mRecentTasks.loadUserRecentsLocked(userId);
7387 }
7388 }
7389
7390 @Override
7391 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7392 synchronized (mGlobalLock) {
7393 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7394 }
7395 }
7396
7397 @Override
7398 public void flushRecentTasks() {
7399 mRecentTasks.flush();
7400 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007401
7402 @Override
7403 public WindowProcessController getHomeProcess() {
7404 synchronized (mGlobalLock) {
7405 return mHomeProcess;
7406 }
7407 }
7408
7409 @Override
7410 public WindowProcessController getPreviousProcess() {
7411 synchronized (mGlobalLock) {
7412 return mPreviousProcess;
7413 }
7414 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007415
7416 @Override
7417 public void clearLockedTasks(String reason) {
7418 synchronized (mGlobalLock) {
7419 getLockTaskController().clearLockedTasks(reason);
7420 }
7421 }
7422
7423 @Override
7424 public void updateUserConfiguration() {
7425 synchronized (mGlobalLock) {
7426 final Configuration configuration = new Configuration(getGlobalConfiguration());
7427 final int currentUserId = mAmInternal.getCurrentUserId();
7428 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7429 configuration, currentUserId, Settings.System.canWrite(mContext));
7430 updateConfigurationLocked(configuration, null /* starting */,
7431 false /* initLocale */, false /* persistent */, currentUserId,
7432 false /* deferResume */);
7433 }
7434 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007435
7436 @Override
7437 public boolean canShowErrorDialogs() {
7438 synchronized (mGlobalLock) {
7439 return mShowDialogs && !mSleeping && !mShuttingDown
7440 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7441 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7442 mAmInternal.getCurrentUserId())
7443 && !(UserManager.isDeviceInDemoMode(mContext)
7444 && mAmInternal.getCurrentUser().isDemo());
7445 }
7446 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007447
7448 @Override
7449 public void setProfileApp(String profileApp) {
7450 synchronized (mGlobalLock) {
7451 mProfileApp = profileApp;
7452 }
7453 }
7454
7455 @Override
7456 public void setProfileProc(WindowProcessController wpc) {
7457 synchronized (mGlobalLock) {
7458 mProfileProc = wpc;
7459 }
7460 }
7461
7462 @Override
7463 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7464 synchronized (mGlobalLock) {
7465 mProfilerInfo = profilerInfo;
7466 }
7467 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007468
7469 @Override
7470 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7471 synchronized (mGlobalLock) {
7472 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7473 }
7474 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007475
7476 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007477 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7478 boolean reducedResolution) {
7479 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7480 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007481 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007482
7483 @Override
7484 public boolean isUidForeground(int uid) {
7485 synchronized (mGlobalLock) {
7486 return ActivityTaskManagerService.this.isUidForeground(uid);
7487 }
7488 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007489
7490 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007491 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007492 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007493 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007494 }
7495 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007496
7497 @Override
7498 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007499 // Translate package names into UIDs
7500 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007501 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007502 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7503 if (uid >= 0) {
7504 result.add(uid);
7505 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007506 }
7507 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007508 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007509 }
7510 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007511 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007512}