blob: 354891840a7755bdc6fd734fd76c3b0c476c05b8 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
214import android.service.voice.IVoiceInteractionSession;
215import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900216import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.telecom.TelecomManager;
218import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100219import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700221import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700223import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
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;
Robert Carr8a2f9132019-11-11 15:03:15 -0800229import android.view.ITaskOrganizer;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700232import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700236import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700238import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700243import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
244import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700246import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.internal.policy.IKeyguardDismissCallback;
248import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700249import com.android.internal.util.ArrayUtils;
250import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700251import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800252import com.android.internal.util.function.pooled.PooledConsumer;
253import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700254import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700255import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.LocalServices;
257import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700258import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800259import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700260import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerService;
262import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
263import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
264import com.android.server.am.AppTimeTracker;
265import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700266import com.android.server.am.PendingIntentController;
267import com.android.server.am.PendingIntentRecord;
268import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900269import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700270import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700271import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700272import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800273import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700274import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700276
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700278import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700282import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700283import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700284import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800285import java.lang.annotation.ElementType;
286import java.lang.annotation.Retention;
287import java.lang.annotation.RetentionPolicy;
288import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700292import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400294import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700295import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700296import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700297import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700298import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700299import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000300import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700301import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302
303/**
304 * System service for managing activities and their containers (task, stacks, displays,... ).
305 *
306 * {@hide}
307 */
308public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000311 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700312 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
313 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
314 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
315 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700316 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700317
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700320 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700321 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100322 // How long we permit background activity starts after an activity in the process
323 // started or finished.
324 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700325
Wale Ogunwale98875612018-10-12 07:53:02 -0700326 /** Used to indicate that an app transition should be animated. */
327 static final boolean ANIMATE = true;
328
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700329 /** Hardware-reported OpenGLES version. */
330 final int GL_ES_VERSION;
331
Wale Ogunwale31913b52018-10-13 08:29:31 -0700332 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
333 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
334 public static final String DUMP_LASTANR_CMD = "lastanr" ;
335 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
336 public static final String DUMP_STARTER_CMD = "starter" ;
337 public static final String DUMP_CONTAINERS_CMD = "containers" ;
338 public static final String DUMP_RECENTS_CMD = "recents" ;
339 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
340
Wale Ogunwale64258362018-10-16 15:13:37 -0700341 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
342 public static final int RELAUNCH_REASON_NONE = 0;
343 /** This activity is being relaunched due to windowing mode change. */
344 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
345 /** This activity is being relaunched due to a free-resize operation. */
346 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
347
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700348 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700349
Wale Ogunwalef6733932018-06-27 05:14:34 -0700350 /**
351 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
352 * change at runtime. Use mContext for non-UI purposes.
353 */
354 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700356 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700358 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700359 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700360 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800361 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800362 @VisibleForTesting
363 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 PowerManagerInternal mPowerManagerInternal;
365 private UsageStatsManagerInternal mUsageStatsInternal;
366
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700367 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700368 IntentFirewall mIntentFirewall;
369
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700370 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800371 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700373 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800374 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
375 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
376 *
377 * @see WindowManagerThreadPriorityBooster
378 */
379 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700380 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800381 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700382 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700383 private UserManagerService mUserManager;
384 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700385 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800386 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700387 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** All processes currently running that might have a window organized by name. */
389 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100390 /** All processes we currently have running mapped by pid and uid */
391 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700392 /** This is the process holding what we currently consider to be the "home" activity. */
393 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700394 /** The currently running heavy-weight process, if any. */
395 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700396 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700397 /**
398 * This is the process holding the activity the user last visited that is in a different process
399 * from the one they are currently in.
400 */
401 WindowProcessController mPreviousProcess;
402 /** The time at which the previous process was last visible. */
403 long mPreviousProcessVisibleTime;
404
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700405 /** List of intents that were used to start the most recent tasks. */
406 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700407 /** State of external calls telling us if the device is awake or asleep. */
408 private boolean mKeyguardShown = false;
409
410 // Wrapper around VoiceInteractionServiceManager
411 private AssistUtils mAssistUtils;
412
413 // VoiceInteraction session ID that changes for each new request except when
414 // being called for multi-window assist in a single session.
415 private int mViSessionId = 1000;
416
417 // How long to wait in getAssistContextExtras for the activity and foreground services
418 // to respond with the result.
419 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
420
421 // How long top wait when going through the modern assist (which doesn't need to block
422 // on getting this result before starting to launch its UI).
423 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
424
425 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
426 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
427
Alison Cichowlas3e340502018-08-07 17:15:01 -0400428 // Permission tokens are used to temporarily granted a trusted app the ability to call
429 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
430 // showing any appropriate error messages to the user.
431 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
432 10 * MINUTE_IN_MILLIS;
433
434 // How long before the service actually expires a token. This is slightly longer than
435 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
436 // expiration exception.
437 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
438 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
439
440 // How long the service will remember expired tokens, for the purpose of providing error
441 // messaging when a client uses an expired token.
442 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
443 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
444
445 // Activity tokens of system activities that are delegating their call to
446 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
447 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
448
449 // Permission tokens that have expired, but we remember for error reporting.
450 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
451
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700452 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
453
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 // Keeps track of the active voice interaction service component, notified from
455 // VoiceInteractionManagerService
456 ComponentName mActiveVoiceInteractionServiceComponent;
457
Michal Karpinskida34cd42019-04-02 19:46:52 +0100458 // A map userId and all its companion app uids
459 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000460
Wale Ogunwalee2172292018-10-25 10:11:10 -0700461 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700462 KeyguardController mKeyguardController;
463 private final ClientLifecycleManager mLifecycleManager;
464 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700465 /** The controller for all operations related to locktask. */
466 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700467 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700468
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700469 boolean mSuppressResizeConfigChanges;
470
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700471 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700472 new UpdateConfigurationResult();
473
474 static final class UpdateConfigurationResult {
475 // Configuration changes that were updated.
476 int changes;
477 // If the activity was relaunched to match the new configuration.
478 boolean activityRelaunched;
479
480 void reset() {
481 changes = 0;
482 activityRelaunched = false;
483 }
484 }
485
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private int mConfigurationSeq;
488 // To cache the list of supported system locales
489 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700490
491 /**
492 * Temp object used when global and/or display override configuration is updated. It is also
493 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
494 * anyone...
495 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700496 private Configuration mTempConfig = new Configuration();
497
Wale Ogunwalef6733932018-06-27 05:14:34 -0700498 /** Temporary to avoid allocations. */
499 final StringBuilder mStringBuilder = new StringBuilder(256);
500
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 // Amount of time after a call to stopAppSwitches() during which we will
502 // prevent further untrusted switches from happening.
503 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
504
505 /**
506 * The time at which we will allow normal application switches again,
507 * after a call to {@link #stopAppSwitches()}.
508 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700509 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700510 /**
511 * This is set to true after the first switch after mAppSwitchesAllowedTime
512 * is set; any switches after that will clear the time.
513 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700514 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515
Ricky Wai906af482019-06-03 17:25:28 +0100516 /**
517 * Last stop app switches time, apps finished before this time cannot start background activity
518 * even if they are in grace period.
519 */
520 private long mLastStopAppSwitchesTime;
521
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522 IActivityController mController = null;
523 boolean mControllerIsAMonkey = false;
524
Wale Ogunwale214f3482018-10-04 11:00:47 -0700525 final int mFactoryTest;
526
527 /** Used to control how we initialize the service. */
528 ComponentName mTopComponent;
529 String mTopAction = Intent.ACTION_MAIN;
530 String mTopData;
531
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800532 /** Profiling app information. */
533 String mProfileApp = null;
534 WindowProcessController mProfileProc = null;
535 ProfilerInfo mProfilerInfo = null;
536
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700537 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700538 * Dump of the activity state at the time of the last ANR. Cleared after
539 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
540 */
541 String mLastANRState;
542
543 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544 * Used to retain an update lock when the foreground activity is in
545 * immersive mode.
546 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700547 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700548
549 /**
550 * Packages that are being allowed to perform unrestricted app switches. Mapping is
551 * User -> Type -> uid.
552 */
553 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
554
555 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700556 private int mThumbnailWidth;
557 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700558
559 /**
560 * Flag that indicates if multi-window is enabled.
561 *
562 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
563 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
564 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
565 * At least one of the forms of multi-window must be enabled in order for this flag to be
566 * initialized to 'true'.
567 *
568 * @see #mSupportsSplitScreenMultiWindow
569 * @see #mSupportsFreeformWindowManagement
570 * @see #mSupportsPictureInPicture
571 * @see #mSupportsMultiDisplay
572 */
573 boolean mSupportsMultiWindow;
574 boolean mSupportsSplitScreenMultiWindow;
575 boolean mSupportsFreeformWindowManagement;
576 boolean mSupportsPictureInPicture;
577 boolean mSupportsMultiDisplay;
578 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700579 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700580
581 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
582
583 // VR Vr2d Display Id.
584 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700585
Wale Ogunwalef6733932018-06-27 05:14:34 -0700586 /**
587 * Set while we are wanting to sleep, to prevent any
588 * activities from being started/resumed.
589 *
590 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
591 *
592 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
593 * while in the sleep state until there is a pending transition out of sleep, in which case
594 * mSleeping is set to false, and remains false while awake.
595 *
596 * Whether mSleeping can quickly toggled between true/false without the device actually
597 * display changing states is undefined.
598 */
599 private boolean mSleeping = false;
600
601 /**
602 * The process state used for processes that are running the top activities.
603 * This changes between TOP and TOP_SLEEPING to following mSleeping.
604 */
605 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
606
Riddle Hsua0022cd2019-09-09 21:12:41 +0800607 @Retention(RetentionPolicy.SOURCE)
608 @IntDef({
609 LAYOUT_REASON_CONFIG_CHANGED,
610 LAYOUT_REASON_VISIBILITY_CHANGED,
611 })
612 @interface LayoutReason {}
613 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
614 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
615
616 /** The reasons to perform surface placement. */
617 @LayoutReason
618 private int mLayoutReasons;
619
Wale Ogunwalef6733932018-06-27 05:14:34 -0700620 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
621 // automatically. Important for devices without direct input devices.
622 private boolean mShowDialogs = true;
623
624 /** Set if we are shutting down the system, similar to sleeping. */
625 boolean mShuttingDown = false;
626
627 /**
628 * We want to hold a wake lock while running a voice interaction session, since
629 * this may happen with the screen off and we need to keep the CPU running to
630 * be able to continue to interact with the user.
631 */
632 PowerManager.WakeLock mVoiceWakeLock;
633
634 /**
635 * Set while we are running a voice interaction. This overrides sleeping while it is active.
636 */
637 IVoiceInteractionSession mRunningVoice;
638
639 /**
640 * The last resumed activity. This is identical to the current resumed activity most
641 * of the time but could be different when we're pausing one activity before we resume
642 * another activity.
643 */
644 ActivityRecord mLastResumedActivity;
645
646 /**
647 * The activity that is currently being traced as the active resumed activity.
648 *
649 * @see #updateResumedAppTrace
650 */
651 private @Nullable ActivityRecord mTracedResumedActivity;
652
653 /** If non-null, we are tracking the time the user spends in the currently focused app. */
654 AppTimeTracker mCurAppTimeTracker;
655
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700656 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700657
Wale Ogunwale53783742018-09-16 10:21:51 -0700658 /**
659 * Packages that the user has asked to have run in screen size
660 * compatibility mode instead of filling the screen.
661 */
662 CompatModePackages mCompatModePackages;
663
Wale Ogunwalef6733932018-06-27 05:14:34 -0700664 private FontScaleSettingObserver mFontScaleSettingObserver;
665
Robert Carr8a2f9132019-11-11 15:03:15 -0800666 /**
667 * Stores the registration and state of TaskOrganizers in use.
668 */
669 TaskOrganizerController mTaskOrganizerController =
670 new TaskOrganizerController(this, mGlobalLock);
671
Ricky Wai96f5c352019-04-10 18:40:17 +0100672 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000673
Wale Ogunwalef6733932018-06-27 05:14:34 -0700674 private final class FontScaleSettingObserver extends ContentObserver {
675 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
676 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
677
678 public FontScaleSettingObserver() {
679 super(mH);
680 final ContentResolver resolver = mContext.getContentResolver();
681 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
682 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
683 UserHandle.USER_ALL);
684 }
685
686 @Override
687 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
688 if (mFontScaleUri.equals(uri)) {
689 updateFontScaleIfNeeded(userId);
690 } else if (mHideErrorDialogsUri.equals(uri)) {
691 synchronized (mGlobalLock) {
692 updateShouldShowDialogsLocked(getGlobalConfiguration());
693 }
694 }
695 }
696 }
697
Riddle Hsua0536432019-02-16 00:38:59 +0800698 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
699 @Target(ElementType.METHOD)
700 @Retention(RetentionPolicy.SOURCE)
701 @interface HotPath {
702 int NONE = 0;
703 int OOM_ADJUSTMENT = 1;
704 int LRU_UPDATE = 2;
705 int PROCESS_CHANGE = 3;
706 int caller() default NONE;
707 }
708
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800709 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
710 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900711 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800712 mAmInternal.updateOomAdj();
713 }
714 };
715
Charles Chen8d98dd22018-12-26 17:36:54 +0800716 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
717 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700718 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700719 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 mSystemThread = ActivityThread.currentActivityThread();
721 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700722 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800723 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700724 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700725 }
726
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 public void onSystemReady() {
728 synchronized (mGlobalLock) {
729 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
730 PackageManager.FEATURE_CANT_SAVE_STATE);
731 mAssistUtils = new AssistUtils(mContext);
732 mVrController.onSystemReady();
733 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700734 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700735 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700736 }
737
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 public void onInitPowerManagement() {
739 synchronized (mGlobalLock) {
740 mStackSupervisor.initPowerManagement();
741 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
742 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
743 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
744 mVoiceWakeLock.setReferenceCounted(false);
745 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700746 }
747
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700748 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700749 mFontScaleSettingObserver = new FontScaleSettingObserver();
750 }
751
Wale Ogunwale59507092018-10-29 09:00:30 -0700752 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700753 final boolean freeformWindowManagement =
754 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
755 || Settings.Global.getInt(
756 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
757
758 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
759 final boolean supportsPictureInPicture = supportsMultiWindow &&
760 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
761 final boolean supportsSplitScreenMultiWindow =
762 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
763 final boolean supportsMultiDisplay = mContext.getPackageManager()
764 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
766 final boolean forceResizable = Settings.Global.getInt(
767 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700768 final boolean sizeCompatFreeform = Settings.Global.getInt(
769 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700770
771 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900772 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773
774 final Configuration configuration = new Configuration();
775 Settings.System.getConfiguration(resolver, configuration);
776 if (forceRtl) {
777 // This will take care of setting the correct layout direction flags
778 configuration.setLayoutDirection(configuration.locale);
779 }
780
781 synchronized (mGlobalLock) {
782 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700783 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700784 final boolean multiWindowFormEnabled = freeformWindowManagement
785 || supportsSplitScreenMultiWindow
786 || supportsPictureInPicture
787 || supportsMultiDisplay;
788 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
789 mSupportsMultiWindow = true;
790 mSupportsFreeformWindowManagement = freeformWindowManagement;
791 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
792 mSupportsPictureInPicture = supportsPictureInPicture;
793 mSupportsMultiDisplay = supportsMultiDisplay;
794 } else {
795 mSupportsMultiWindow = false;
796 mSupportsFreeformWindowManagement = false;
797 mSupportsSplitScreenMultiWindow = false;
798 mSupportsPictureInPicture = false;
799 mSupportsMultiDisplay = false;
800 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700801 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700802 // This happens before any activities are started, so we can change global configuration
803 // in-place.
804 updateConfigurationLocked(configuration, null, true);
805 final Configuration globalConfig = getGlobalConfiguration();
806 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
807
808 // Load resources only after the current configuration has been set.
809 final Resources res = mContext.getResources();
810 mThumbnailWidth = res.getDimensionPixelSize(
811 com.android.internal.R.dimen.thumbnail_width);
812 mThumbnailHeight = res.getDimensionPixelSize(
813 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700814 }
815 }
816
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800817 public WindowManagerGlobalLock getGlobalLock() {
818 return mGlobalLock;
819 }
820
Yunfan Chen585f2932019-01-29 16:04:45 +0900821 /** For test purpose only. */
822 @VisibleForTesting
823 public ActivityTaskManagerInternal getAtmInternal() {
824 return mInternal;
825 }
826
Riddle Hsud93a6c42018-11-29 21:50:06 +0800827 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
828 Looper looper) {
829 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700830 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700831 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700832 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800833 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700834 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700835 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700838 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700839 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700840 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700841 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700842 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700843 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700844 mKeyguardController = mStackSupervisor.getKeyguardController();
845 }
846
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700847 public void onActivityManagerInternalAdded() {
848 synchronized (mGlobalLock) {
849 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
850 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
851 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700852 }
853
Yunfan Chen75157d72018-07-27 14:47:21 +0900854 int increaseConfigurationSeqLocked() {
855 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
856 return mConfigurationSeq;
857 }
858
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700859 protected ActivityStackSupervisor createStackSupervisor() {
860 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
861 supervisor.initialize();
862 return supervisor;
863 }
864
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800865 protected AppWarnings createAppWarnings(
866 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
867 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
868 }
869
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700870 public void setWindowManager(WindowManagerService wm) {
871 synchronized (mGlobalLock) {
872 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800874 mTempConfig.setToDefaults();
875 mTempConfig.setLocales(LocaleList.getDefault());
876 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800877 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700878 mLockTaskController.setWindowManager(wm);
879 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800880 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700881 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700882 }
883
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700884 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
885 synchronized (mGlobalLock) {
886 mUsageStatsInternal = usageStatsManager;
887 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700888 }
889
Wale Ogunwalef6733932018-06-27 05:14:34 -0700890 UserManagerService getUserManager() {
891 if (mUserManager == null) {
892 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
893 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
894 }
895 return mUserManager;
896 }
897
898 AppOpsService getAppOpsService() {
899 if (mAppOpsService == null) {
900 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
901 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
902 }
903 return mAppOpsService;
904 }
905
906 boolean hasUserRestriction(String restriction, int userId) {
907 return getUserManager().hasUserRestriction(restriction, userId);
908 }
909
Michal Karpinski15486842019-04-25 17:33:42 +0100910 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
911 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800912 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100913 if (mode == AppOpsManager.MODE_DEFAULT) {
914 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
915 == PERMISSION_GRANTED;
916 }
917 return mode == AppOpsManager.MODE_ALLOWED;
918 }
919
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700920 @VisibleForTesting
921 protected void setRecentTasks(RecentTasks recentTasks) {
922 mRecentTasks = recentTasks;
923 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700924 }
925
926 RecentTasks getRecentTasks() {
927 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700928 }
929
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700930 ClientLifecycleManager getLifecycleManager() {
931 return mLifecycleManager;
932 }
933
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700934 ActivityStartController getActivityStartController() {
935 return mActivityStartController;
936 }
937
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700938 TaskChangeNotificationController getTaskChangeNotificationController() {
939 return mTaskChangeNotificationController;
940 }
941
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700942 LockTaskController getLockTaskController() {
943 return mLockTaskController;
944 }
945
Yunfan Chen75157d72018-07-27 14:47:21 +0900946 /**
947 * Return the global configuration used by the process corresponding to the input pid. This is
948 * usually the global configuration with some overrides specific to that process.
949 */
950 Configuration getGlobalConfigurationForCallingPid() {
951 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800952 return getGlobalConfigurationForPid(pid);
953 }
954
955 /**
956 * Return the global configuration used by the process corresponding to the given pid.
957 */
958 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900959 if (pid == MY_PID || pid < 0) {
960 return getGlobalConfiguration();
961 }
962 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100963 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900964 return app != null ? app.getConfiguration() : getGlobalConfiguration();
965 }
966 }
967
968 /**
969 * Return the device configuration info used by the process corresponding to the input pid.
970 * The value is consistent with the global configuration for the process.
971 */
972 @Override
973 public ConfigurationInfo getDeviceConfigurationInfo() {
974 ConfigurationInfo config = new ConfigurationInfo();
975 synchronized (mGlobalLock) {
976 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
977 config.reqTouchScreen = globalConfig.touchscreen;
978 config.reqKeyboardType = globalConfig.keyboard;
979 config.reqNavigation = globalConfig.navigation;
980 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
981 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
982 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
983 }
984 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
985 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
986 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
987 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700988 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900989 }
990 return config;
991 }
992
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700993 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700994 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700995 }
996
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700997 public static final class Lifecycle extends SystemService {
998 private final ActivityTaskManagerService mService;
999
1000 public Lifecycle(Context context) {
1001 super(context);
1002 mService = new ActivityTaskManagerService(context);
1003 }
1004
1005 @Override
1006 public void onStart() {
1007 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001008 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001009 }
1010
Garfield Tan891146c2018-10-09 12:14:00 -07001011 @Override
1012 public void onUnlockUser(int userId) {
1013 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001014 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001015 }
1016 }
1017
1018 @Override
1019 public void onCleanupUser(int userId) {
1020 synchronized (mService.getGlobalLock()) {
1021 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1022 }
1023 }
1024
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001025 public ActivityTaskManagerService getService() {
1026 return mService;
1027 }
1028 }
1029
1030 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001031 public final int startActivity(IApplicationThread caller, String callingPackage,
1032 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1033 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1034 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1035 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1036 UserHandle.getCallingUserId());
1037 }
1038
1039 @Override
1040 public final int startActivities(IApplicationThread caller, String callingPackage,
1041 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1042 int userId) {
1043 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001044 enforceNotIsolatedCaller(reason);
1045 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001047 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1048 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1049 reason, null /* originatingPendingIntent */,
1050 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001051 }
1052
1053 @Override
1054 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1055 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1056 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1057 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1058 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1059 true /*validateIncomingUser*/);
1060 }
1061
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001062 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1064 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1065 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001066 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001068 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1070
1071 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001072 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001073 .setCaller(caller)
1074 .setCallingPackage(callingPackage)
1075 .setResolvedType(resolvedType)
1076 .setResultTo(resultTo)
1077 .setResultWho(resultWho)
1078 .setRequestCode(requestCode)
1079 .setStartFlags(startFlags)
1080 .setProfilerInfo(profilerInfo)
1081 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001082 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 .execute();
1084
1085 }
1086
1087 @Override
1088 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1089 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001090 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1091 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001092 // Refuse possible leaked file descriptors
1093 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1094 throw new IllegalArgumentException("File descriptors passed in Intent");
1095 }
1096
1097 if (!(target instanceof PendingIntentRecord)) {
1098 throw new IllegalArgumentException("Bad PendingIntent object");
1099 }
1100
1101 PendingIntentRecord pir = (PendingIntentRecord)target;
1102
1103 synchronized (mGlobalLock) {
1104 // If this is coming from the currently resumed activity, it is
1105 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001106 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 if (stack.mResumedActivity != null &&
1108 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001109 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001110 }
1111 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001112 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 }
1115
1116 @Override
1117 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1118 Bundle bOptions) {
1119 // Refuse possible leaked file descriptors
1120 if (intent != null && intent.hasFileDescriptors()) {
1121 throw new IllegalArgumentException("File descriptors passed in Intent");
1122 }
1123 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1124
1125 synchronized (mGlobalLock) {
1126 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1127 if (r == null) {
1128 SafeActivityOptions.abort(options);
1129 return false;
1130 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001131 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001132 // The caller is not running... d'oh!
1133 SafeActivityOptions.abort(options);
1134 return false;
1135 }
1136 intent = new Intent(intent);
1137 // The caller is not allowed to change the data.
1138 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1139 // And we are resetting to find the next component...
1140 intent.setComponent(null);
1141
1142 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1143
1144 ActivityInfo aInfo = null;
1145 try {
1146 List<ResolveInfo> resolves =
1147 AppGlobals.getPackageManager().queryIntentActivities(
1148 intent, r.resolvedType,
1149 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1150 UserHandle.getCallingUserId()).getList();
1151
1152 // Look for the original activity in the list...
1153 final int N = resolves != null ? resolves.size() : 0;
1154 for (int i=0; i<N; i++) {
1155 ResolveInfo rInfo = resolves.get(i);
1156 if (rInfo.activityInfo.packageName.equals(r.packageName)
1157 && rInfo.activityInfo.name.equals(r.info.name)) {
1158 // We found the current one... the next matching is
1159 // after it.
1160 i++;
1161 if (i<N) {
1162 aInfo = resolves.get(i).activityInfo;
1163 }
1164 if (debug) {
1165 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1166 + "/" + r.info.name);
1167 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1168 ? "null" : aInfo.packageName + "/" + aInfo.name));
1169 }
1170 break;
1171 }
1172 }
1173 } catch (RemoteException e) {
1174 }
1175
1176 if (aInfo == null) {
1177 // Nobody who is next!
1178 SafeActivityOptions.abort(options);
1179 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1180 return false;
1181 }
1182
1183 intent.setComponent(new ComponentName(
1184 aInfo.applicationInfo.packageName, aInfo.name));
1185 intent.setFlags(intent.getFlags()&~(
1186 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1187 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1188 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1189 FLAG_ACTIVITY_NEW_TASK));
1190
1191 // Okay now we need to start the new activity, replacing the currently running activity.
1192 // This is a little tricky because we want to start the new one as if the current one is
1193 // finished, but not finish the current one first so that there is no flicker.
1194 // And thus...
1195 final boolean wasFinishing = r.finishing;
1196 r.finishing = true;
1197
1198 // Propagate reply information over to the new activity.
1199 final ActivityRecord resultTo = r.resultTo;
1200 final String resultWho = r.resultWho;
1201 final int requestCode = r.requestCode;
1202 r.resultTo = null;
1203 if (resultTo != null) {
1204 resultTo.removeResultsLocked(r, resultWho, requestCode);
1205 }
1206
1207 final long origId = Binder.clearCallingIdentity();
1208 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001209 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001211 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 .setResolvedType(r.resolvedType)
1213 .setActivityInfo(aInfo)
1214 .setResultTo(resultTo != null ? resultTo.appToken : null)
1215 .setResultWho(resultWho)
1216 .setRequestCode(requestCode)
1217 .setCallingPid(-1)
1218 .setCallingUid(r.launchedFromUid)
1219 .setCallingPackage(r.launchedFromPackage)
1220 .setRealCallingPid(-1)
1221 .setRealCallingUid(r.launchedFromUid)
1222 .setActivityOptions(options)
1223 .execute();
1224 Binder.restoreCallingIdentity(origId);
1225
1226 r.finishing = wasFinishing;
1227 if (res != ActivityManager.START_SUCCESS) {
1228 return false;
1229 }
1230 return true;
1231 }
1232 }
1233
1234 @Override
1235 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1236 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1237 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1238 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001239 enforceNotIsolatedCaller("startActivityAndWait");
1240 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1241 userId, "startActivityAndWait");
1242 // TODO: Switch to user app stacks here.
1243 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1244 .setCaller(caller)
1245 .setCallingPackage(callingPackage)
1246 .setResolvedType(resolvedType)
1247 .setResultTo(resultTo)
1248 .setResultWho(resultWho)
1249 .setRequestCode(requestCode)
1250 .setStartFlags(startFlags)
1251 .setActivityOptions(bOptions)
1252 .setUserId(userId)
1253 .setProfilerInfo(profilerInfo)
1254 .setWaitResult(res)
1255 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001256 return res;
1257 }
1258
1259 @Override
1260 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1261 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1262 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001263 enforceNotIsolatedCaller("startActivityWithConfig");
1264 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1265 "startActivityWithConfig");
1266 // TODO: Switch to user app stacks here.
1267 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1268 .setCaller(caller)
1269 .setCallingPackage(callingPackage)
1270 .setResolvedType(resolvedType)
1271 .setResultTo(resultTo)
1272 .setResultWho(resultWho)
1273 .setRequestCode(requestCode)
1274 .setStartFlags(startFlags)
1275 .setGlobalConfiguration(config)
1276 .setActivityOptions(bOptions)
1277 .setUserId(userId)
1278 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 }
1280
Robert Carr8a2f9132019-11-11 15:03:15 -08001281 @Override
1282 public final void registerTaskOrganizer(ITaskOrganizer organizer, int windowingMode) {
1283 enforceCallerIsRecentsOrHasPermission(
1284 MANAGE_ACTIVITY_STACKS, "registerTaskOrganizer()");
1285 synchronized (mGlobalLock) {
1286 mTaskOrganizerController.registerTaskOrganizer(organizer, windowingMode);
1287 }
1288 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001289
1290 @Override
1291 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1292 int callingUid = Binder.getCallingUid();
1293 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1294 throw new SecurityException("Only the system process can request a permission token, "
1295 + "received request from uid: " + callingUid);
1296 }
1297 IBinder permissionToken = new Binder();
1298 synchronized (mGlobalLock) {
1299 mStartActivitySources.put(permissionToken, delegatorToken);
1300 }
1301
1302 Message expireMsg = PooledLambda.obtainMessage(
1303 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1304 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1305
1306 Message forgetMsg = PooledLambda.obtainMessage(
1307 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1308 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1309
1310 return permissionToken;
1311 }
1312
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001313 @Override
1314 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1315 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001316 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1317 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001318 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319 // permission grants) as any app that may launch one of your own activities. So we only
1320 // allow this in two cases:
1321 // 1) The caller is an activity that is part of the core framework, and then only when it
1322 // is running as the system.
1323 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1324 // can only be requested by a system activity, which may then delegate this call to
1325 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 final ActivityRecord sourceRecord;
1327 final int targetUid;
1328 final String targetPackage;
1329 final boolean isResolver;
1330 synchronized (mGlobalLock) {
1331 if (resultTo == null) {
1332 throw new SecurityException("Must be called from an activity");
1333 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001334 final IBinder sourceToken;
1335 if (permissionToken != null) {
1336 // To even attempt to use a permissionToken, an app must also have this signature
1337 // permission.
1338 mAmInternal.enforceCallingPermission(
1339 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1340 "startActivityAsCaller");
1341 // If called with a permissionToken, we want the sourceRecord from the delegator
1342 // activity that requested this token.
1343 sourceToken = mStartActivitySources.remove(permissionToken);
1344 if (sourceToken == null) {
1345 // Invalid permissionToken, check if it recently expired.
1346 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1347 throw new SecurityException("Called with expired permission token: "
1348 + permissionToken);
1349 } else {
1350 throw new SecurityException("Called with invalid permission token: "
1351 + permissionToken);
1352 }
1353 }
1354 } else {
1355 // This method was called directly by the source.
1356 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001358
Louis Chang149d5c82019-12-30 09:47:39 +08001359 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001360 if (sourceRecord == null) {
1361 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 }
1363 if (sourceRecord.app == null) {
1364 throw new SecurityException("Called without a process attached to activity");
1365 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001366
1367 // Whether called directly or from a delegate, the source activity must be from the
1368 // android package.
1369 if (!sourceRecord.info.packageName.equals("android")) {
1370 throw new SecurityException("Must be called from an activity that is "
1371 + "declared in the android package");
1372 }
1373
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001374 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001375 // This is still okay, as long as this activity is running under the
1376 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001377 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001379 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 + " must be system uid or original calling uid "
1381 + sourceRecord.launchedFromUid);
1382 }
1383 }
1384 if (ignoreTargetSecurity) {
1385 if (intent.getComponent() == null) {
1386 throw new SecurityException(
1387 "Component must be specified with ignoreTargetSecurity");
1388 }
1389 if (intent.getSelector() != null) {
1390 throw new SecurityException(
1391 "Selector not allowed with ignoreTargetSecurity");
1392 }
1393 }
1394 targetUid = sourceRecord.launchedFromUid;
1395 targetPackage = sourceRecord.launchedFromPackage;
1396 isResolver = sourceRecord.isResolverOrChildActivity();
1397 }
1398
1399 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001400 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 }
1402
1403 // TODO: Switch to user app stacks here.
1404 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001405 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 .setCallingUid(targetUid)
1407 .setCallingPackage(targetPackage)
1408 .setResolvedType(resolvedType)
1409 .setResultTo(resultTo)
1410 .setResultWho(resultWho)
1411 .setRequestCode(requestCode)
1412 .setStartFlags(startFlags)
1413 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001414 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1416 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001417 // The target may well be in the background, which would normally prevent it
1418 // from starting an activity. Here we definitely want the start to succeed.
1419 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 .execute();
1421 } catch (SecurityException e) {
1422 // XXX need to figure out how to propagate to original app.
1423 // A SecurityException here is generally actually a fault of the original
1424 // calling activity (such as a fairly granting permissions), so propagate it
1425 // back to them.
1426 /*
1427 StringBuilder msg = new StringBuilder();
1428 msg.append("While launching");
1429 msg.append(intent.toString());
1430 msg.append(": ");
1431 msg.append(e.getMessage());
1432 */
1433 throw e;
1434 }
1435 }
1436
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1438 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1439 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1440 }
1441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 @Override
1443 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1444 Intent intent, String resolvedType, IVoiceInteractionSession session,
1445 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1446 Bundle bOptions, int userId) {
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)
1456 .setResolvedType(resolvedType)
1457 .setVoiceSession(session)
1458 .setVoiceInteractor(interactor)
1459 .setStartFlags(startFlags)
1460 .setProfilerInfo(profilerInfo)
1461 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001462 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001463 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 .execute();
1465 }
1466
1467 @Override
1468 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1469 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001470 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1471 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001473 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 .setCallingUid(callingUid)
1475 .setCallingPackage(callingPackage)
1476 .setResolvedType(resolvedType)
1477 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001478 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001479 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 .execute();
1481 }
1482
Riddle Hsu609a8e22019-06-27 16:46:29 -06001483 /**
1484 * Start the recents activity to perform the recents animation.
1485 *
1486 * @param intent The intent to start the recents activity.
1487 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1488 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001490 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1491 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001492 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001494 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 final long origId = Binder.clearCallingIdentity();
1496 try {
1497 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001498 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1499 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001500 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001501
1502 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001503 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001504 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001505 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001506 if (recentsAnimationRunner == null) {
1507 anim.preloadRecentsActivity();
1508 } else {
1509 anim.startRecentsActivity(recentsAnimationRunner);
1510 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 }
1512 } finally {
1513 Binder.restoreCallingIdentity(origId);
1514 }
1515 }
1516
1517 @Override
1518 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001519 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 "startActivityFromRecents()");
1521
1522 final int callingPid = Binder.getCallingPid();
1523 final int callingUid = Binder.getCallingUid();
1524 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1525 final long origId = Binder.clearCallingIdentity();
1526 try {
1527 synchronized (mGlobalLock) {
1528 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1529 safeOptions);
1530 }
1531 } finally {
1532 Binder.restoreCallingIdentity(origId);
1533 }
1534 }
1535
1536 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001537 * Public API to check if the client is allowed to start an activity on specified display.
1538 *
1539 * If the target display is private or virtual, some restrictions will apply.
1540 *
1541 * @param displayId Target display id.
1542 * @param intent Intent used to launch the activity.
1543 * @param resolvedType The MIME type of the intent.
1544 * @param userId The id of the user for whom the call is made.
1545 * @return {@code true} if a call to start an activity on the target display should succeed and
1546 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1547 */
1548 @Override
1549 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1550 String resolvedType, int userId) {
1551 final int callingUid = Binder.getCallingUid();
1552 final int callingPid = Binder.getCallingPid();
1553 final long origId = Binder.clearCallingIdentity();
1554
1555 try {
1556 // Collect information about the target of the Intent.
1557 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1558 0 /* startFlags */, null /* profilerInfo */, userId,
1559 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1560 UserHandle.USER_NULL));
1561 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1562
1563 synchronized (mGlobalLock) {
1564 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1565 aInfo);
1566 }
1567 } finally {
1568 Binder.restoreCallingIdentity(origId);
1569 }
1570 }
1571
1572 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 * This is the internal entry point for handling Activity.finish().
1574 *
1575 * @param token The Binder token referencing the Activity we want to finish.
1576 * @param resultCode Result code, if any, from this Activity.
1577 * @param resultData Result data (Intent), if any, from this Activity.
1578 * @param finishTask Whether to finish the task associated with this Activity.
1579 *
1580 * @return Returns true if the activity successfully finished, or false if it is still running.
1581 */
1582 @Override
1583 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1584 int finishTask) {
1585 // Refuse possible leaked file descriptors
1586 if (resultData != null && resultData.hasFileDescriptors()) {
1587 throw new IllegalArgumentException("File descriptors passed in Intent");
1588 }
1589
1590 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001591 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 if (r == null) {
1593 return true;
1594 }
1595 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001596 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001597 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 if (rootR == null) {
1599 Slog.w(TAG, "Finishing task with all activities already finished");
1600 }
1601 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1602 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001603 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001604 return false;
1605 }
1606
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001607 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1608 // We should consolidate.
1609 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001611 final ActivityRecord next =
1612 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 if (next != null) {
1614 // ask watcher if this is allowed
1615 boolean resumeOK = true;
1616 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001617 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001619 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 Watchdog.getInstance().setActivityController(null);
1621 }
1622
1623 if (!resumeOK) {
1624 Slog.i(TAG, "Not finishing activity because controller resumed");
1625 return false;
1626 }
1627 }
1628 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001629
1630 // note down that the process has finished an activity and is in background activity
1631 // starts grace period
1632 if (r.app != null) {
1633 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1634 }
1635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001636 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001637 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 try {
1639 boolean res;
1640 final boolean finishWithRootActivity =
1641 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1642 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1643 || (finishWithRootActivity && r == rootR)) {
1644 // If requested, remove the task that is associated to this activity only if it
1645 // was the root activity in the task. The result code and data is ignored
1646 // because we don't support returning them across task boundaries. Also, to
1647 // keep backwards compatibility we remove the task from recents when finishing
1648 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001649 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001651 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001652 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001653 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001655 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001656 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 if (!res) {
1658 Slog.i(TAG, "Failed to finish by app-request");
1659 }
1660 }
1661 return res;
1662 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001663 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001664 Binder.restoreCallingIdentity(origId);
1665 }
1666 }
1667 }
1668
1669 @Override
1670 public boolean finishActivityAffinity(IBinder token) {
1671 synchronized (mGlobalLock) {
1672 final long origId = Binder.clearCallingIdentity();
1673 try {
1674 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1675 if (r == null) {
1676 return false;
1677 }
1678
1679 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1680 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001681 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001682 return false;
1683 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001684
1685 final PooledFunction p = PooledLambda.obtainFunction(
1686 ActivityRecord::finishIfSameAffinity, r,
1687 PooledLambda.__(ActivityRecord.class));
1688 r.getTask().forAllActivities(
1689 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1690 p.recycle();
1691
Andrii Kuliande93eff2019-07-12 12:21:27 -07001692 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 } finally {
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696 }
1697 }
1698
1699 @Override
1700 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1701 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001702 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001703 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001704 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001705 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1706 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001707 return;
1708 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001709 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1710 false /* processPausingActivities */, config);
1711 if (stopProfiling && r.hasProcess()) {
1712 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 }
1714 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001715 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001716 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001717 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 }
1720
1721 @Override
1722 public final void activityResumed(IBinder token) {
1723 final long origId = Binder.clearCallingIdentity();
1724 synchronized (mGlobalLock) {
1725 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 }
1727 Binder.restoreCallingIdentity(origId);
1728 }
1729
1730 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001731 public final void activityTopResumedStateLost() {
1732 final long origId = Binder.clearCallingIdentity();
1733 synchronized (mGlobalLock) {
1734 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1735 }
1736 Binder.restoreCallingIdentity(origId);
1737 }
1738
1739 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 public final void activityPaused(IBinder token) {
1741 final long origId = Binder.clearCallingIdentity();
1742 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001743 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001744 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1745 if (r != null) {
1746 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001748 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001749 }
1750 Binder.restoreCallingIdentity(origId);
1751 }
1752
1753 @Override
1754 public final void activityStopped(IBinder token, Bundle icicle,
1755 PersistableBundle persistentState, CharSequence description) {
1756 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1757
1758 // Refuse possible leaked file descriptors
1759 if (icicle != null && icicle.hasFileDescriptors()) {
1760 throw new IllegalArgumentException("File descriptors passed in Bundle");
1761 }
1762
1763 final long origId = Binder.clearCallingIdentity();
1764
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001765 String restartingName = null;
1766 int restartingUid = 0;
1767 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001768 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001769 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001770 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001772 if (r.attachedToProcess()
1773 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1774 // The activity was requested to restart from
1775 // {@link #restartActivityProcessIfVisible}.
1776 restartingName = r.app.mName;
1777 restartingUid = r.app.mUid;
1778 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001779 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001780 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001781 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782 }
1783
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001784 if (restartingName != null) {
1785 // In order to let the foreground activity can be restarted with its saved state from
1786 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1787 // until the activity reports stopped with the state. And the activity record will be
1788 // kept because the record state is restarting, then the activity will be restarted
1789 // immediately if it is still the top one.
1790 mStackSupervisor.removeRestartTimeouts(r);
1791 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1792 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001793 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001794
1795 Binder.restoreCallingIdentity(origId);
1796 }
1797
1798 @Override
1799 public final void activityDestroyed(IBinder token) {
1800 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1801 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001802 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001803 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001804 try {
1805 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1806 if (activity != null) {
1807 activity.destroyed("activityDestroyed");
1808 }
1809 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001810 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001811 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 }
1813 }
1814 }
1815
1816 @Override
1817 public final void activityRelaunched(IBinder token) {
1818 final long origId = Binder.clearCallingIdentity();
1819 synchronized (mGlobalLock) {
1820 mStackSupervisor.activityRelaunchedLocked(token);
1821 }
1822 Binder.restoreCallingIdentity(origId);
1823 }
1824
1825 public final void activitySlept(IBinder token) {
1826 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1827
1828 final long origId = Binder.clearCallingIdentity();
1829
1830 synchronized (mGlobalLock) {
1831 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1832 if (r != null) {
1833 mStackSupervisor.activitySleptLocked(r);
1834 }
1835 }
1836
1837 Binder.restoreCallingIdentity(origId);
1838 }
1839
1840 @Override
1841 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1842 synchronized (mGlobalLock) {
1843 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1844 if (r == null) {
1845 return;
1846 }
1847 final long origId = Binder.clearCallingIdentity();
1848 try {
1849 r.setRequestedOrientation(requestedOrientation);
1850 } finally {
1851 Binder.restoreCallingIdentity(origId);
1852 }
1853 }
1854 }
1855
1856 @Override
1857 public int getRequestedOrientation(IBinder token) {
1858 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001859 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1860 return (r != null)
1861 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001862 }
1863 }
1864
1865 @Override
1866 public void setImmersive(IBinder token, boolean immersive) {
1867 synchronized (mGlobalLock) {
1868 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1869 if (r == null) {
1870 throw new IllegalArgumentException();
1871 }
1872 r.immersive = immersive;
1873
1874 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001875 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001877 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 }
1879 }
1880 }
1881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001882 void applyUpdateLockStateLocked(ActivityRecord r) {
1883 // Modifications to the UpdateLock state are done on our handler, outside
1884 // the activity manager's locks. The new state is determined based on the
1885 // state *now* of the relevant activity record. The object is passed to
1886 // the handler solely for logging detail, not to be consulted/modified.
1887 final boolean nextState = r != null && r.immersive;
1888 mH.post(() -> {
1889 if (mUpdateLock.isHeld() != nextState) {
1890 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1891 "Applying new update lock state '" + nextState + "' for " + r);
1892 if (nextState) {
1893 mUpdateLock.acquire();
1894 } else {
1895 mUpdateLock.release();
1896 }
1897 }
1898 });
1899 }
1900
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 @Override
1902 public boolean isImmersive(IBinder token) {
1903 synchronized (mGlobalLock) {
1904 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1905 if (r == null) {
1906 throw new IllegalArgumentException();
1907 }
1908 return r.immersive;
1909 }
1910 }
1911
1912 @Override
1913 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001914 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001916 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001917 return (r != null) ? r.immersive : false;
1918 }
1919 }
1920
1921 @Override
1922 public void overridePendingTransition(IBinder token, String packageName,
1923 int enterAnim, int exitAnim) {
1924 synchronized (mGlobalLock) {
1925 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1926 if (self == null) {
1927 return;
1928 }
1929
1930 final long origId = Binder.clearCallingIdentity();
1931
1932 if (self.isState(
1933 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001934 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001935 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 }
1937
1938 Binder.restoreCallingIdentity(origId);
1939 }
1940 }
1941
1942 @Override
1943 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001944 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001946 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 if (r == null) {
1948 return ActivityManager.COMPAT_MODE_UNKNOWN;
1949 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001950 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 }
1952 }
1953
1954 @Override
1955 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001956 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001958 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001960 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 if (r == null) {
1962 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1963 return;
1964 }
1965 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001966 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 }
1968 }
1969
1970 @Override
1971 public int getLaunchedFromUid(IBinder activityToken) {
1972 ActivityRecord srec;
1973 synchronized (mGlobalLock) {
1974 srec = ActivityRecord.forTokenLocked(activityToken);
1975 }
1976 if (srec == null) {
1977 return -1;
1978 }
1979 return srec.launchedFromUid;
1980 }
1981
1982 @Override
1983 public String getLaunchedFromPackage(IBinder activityToken) {
1984 ActivityRecord srec;
1985 synchronized (mGlobalLock) {
1986 srec = ActivityRecord.forTokenLocked(activityToken);
1987 }
1988 if (srec == null) {
1989 return null;
1990 }
1991 return srec.launchedFromPackage;
1992 }
1993
1994 @Override
1995 public boolean convertFromTranslucent(IBinder token) {
1996 final long origId = Binder.clearCallingIdentity();
1997 try {
1998 synchronized (mGlobalLock) {
1999 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2000 if (r == null) {
2001 return false;
2002 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002003 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002004 }
2005 } finally {
2006 Binder.restoreCallingIdentity(origId);
2007 }
2008 }
2009
2010 @Override
2011 public boolean convertToTranslucent(IBinder token, Bundle options) {
2012 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2013 final long origId = Binder.clearCallingIdentity();
2014 try {
2015 synchronized (mGlobalLock) {
2016 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2017 if (r == null) {
2018 return false;
2019 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002020 final ActivityRecord under = r.getTask().getActivityBelow(r);
2021 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2023 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002024 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 }
2026 } finally {
2027 Binder.restoreCallingIdentity(origId);
2028 }
2029 }
2030
2031 @Override
2032 public void notifyActivityDrawn(IBinder token) {
2033 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2034 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002035 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002036 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002037 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 }
2039 }
2040 }
2041
2042 @Override
2043 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2044 synchronized (mGlobalLock) {
2045 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2046 if (r == null) {
2047 return;
2048 }
2049 r.reportFullyDrawnLocked(restoredFromBundle);
2050 }
2051 }
2052
2053 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002054 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 synchronized (mGlobalLock) {
2056 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08002057 if (stack != null && stack.getDisplayId() != INVALID_DISPLAY) {
2058 return stack.getDisplayId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 }
2060 return DEFAULT_DISPLAY;
2061 }
2062 }
2063
2064 @Override
2065 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 long ident = Binder.clearCallingIdentity();
2068 try {
2069 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002070 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 if (focusedStack != null) {
Louis Chang149d5c82019-12-30 09:47:39 +08002072 return mRootWindowContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 }
2074 return null;
2075 }
2076 } finally {
2077 Binder.restoreCallingIdentity(ident);
2078 }
2079 }
2080
2081 @Override
2082 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002083 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2085 final long callingId = Binder.clearCallingIdentity();
2086 try {
2087 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002088 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002089 if (stack == null) {
2090 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2091 return;
2092 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002093 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002094 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002095 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 }
2097 }
2098 } finally {
2099 Binder.restoreCallingIdentity(callingId);
2100 }
2101 }
2102
2103 @Override
2104 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002105 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2107 final long callingId = Binder.clearCallingIdentity();
2108 try {
2109 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002110 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002111 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 if (task == null) {
2113 return;
2114 }
2115 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002116 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002117 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 }
2119 }
2120 } finally {
2121 Binder.restoreCallingIdentity(callingId);
2122 }
2123 }
2124
2125 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002126 public void restartActivityProcessIfVisible(IBinder activityToken) {
2127 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2128 final long callingId = Binder.clearCallingIdentity();
2129 try {
2130 synchronized (mGlobalLock) {
2131 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2132 if (r == null) {
2133 return;
2134 }
2135 r.restartProcessIfVisible();
2136 }
2137 } finally {
2138 Binder.restoreCallingIdentity(callingId);
2139 }
2140 }
2141
2142 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002143 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002144 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 synchronized (mGlobalLock) {
2146 final long ident = Binder.clearCallingIdentity();
2147 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002148 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 "remove-task");
2150 } finally {
2151 Binder.restoreCallingIdentity(ident);
2152 }
2153 }
2154 }
2155
2156 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002157 public void removeAllVisibleRecentTasks() {
2158 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2159 synchronized (mGlobalLock) {
2160 final long ident = Binder.clearCallingIdentity();
2161 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002162 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002163 } finally {
2164 Binder.restoreCallingIdentity(ident);
2165 }
2166 }
2167 }
2168
2169 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2171 synchronized (mGlobalLock) {
2172 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2173 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002174 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 }
2176 }
2177 return false;
2178 }
2179
2180 @Override
2181 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2182 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002183
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002184 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002185 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2186 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002187 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002188 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002189 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002190 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 }
2192 }
2193
2194 /**
2195 * Attempts to move a task backwards in z-order (the order of activities within the task is
2196 * unchanged).
2197 *
2198 * There are several possible results of this call:
2199 * - if the task is locked, then we will show the lock toast
2200 * - if there is a task behind the provided task, then that task is made visible and resumed as
2201 * this task is moved to the back
2202 * - otherwise, if there are no other tasks in the stack:
2203 * - if this task is in the pinned stack, then we remove the stack completely, which will
2204 * have the effect of moving the task to the top or bottom of the fullscreen stack
2205 * (depending on whether it is visible)
2206 * - otherwise, we simply return home and hide this task
2207 *
2208 * @param token A reference to the activity we wish to move
2209 * @param nonRoot If false then this only works if the activity is the root
2210 * of a task; if true it will work for any activity in a task.
2211 * @return Returns true if the move completed, false if not.
2212 */
2213 @Override
2214 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002215 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002216 synchronized (mGlobalLock) {
2217 final long origId = Binder.clearCallingIdentity();
2218 try {
2219 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002220 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002222 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 }
2224 } finally {
2225 Binder.restoreCallingIdentity(origId);
2226 }
2227 }
2228 return false;
2229 }
2230
2231 @Override
2232 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002233 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002234 long ident = Binder.clearCallingIdentity();
2235 Rect rect = new Rect();
2236 try {
2237 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002238 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2240 if (task == null) {
2241 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2242 return rect;
2243 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002244 if (task.getParent() != null) {
2245 rect.set(task.getBounds());
2246 } else if (task.mLastNonFullscreenBounds != null) {
2247 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 }
2249 }
2250 } finally {
2251 Binder.restoreCallingIdentity(ident);
2252 }
2253 return rect;
2254 }
2255
2256 @Override
2257 public ActivityManager.TaskDescription getTaskDescription(int id) {
2258 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002260 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002261 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2263 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002264 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265 }
2266 }
2267 return null;
2268 }
2269
2270 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2272 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2273 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2274 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2275 return;
2276 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002277 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002278 synchronized (mGlobalLock) {
2279 final long ident = Binder.clearCallingIdentity();
2280 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002281 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002282 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002283 if (task == null) {
2284 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2285 return;
2286 }
2287
2288 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2289 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2290
2291 if (!task.isActivityTypeStandardOrUndefined()) {
2292 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2293 + " non-standard task " + taskId + " to windowing mode="
2294 + windowingMode);
2295 }
2296
2297 final ActivityStack stack = task.getStack();
2298 if (toTop) {
2299 stack.moveToFront("setTaskWindowingMode", task);
2300 }
2301 stack.setWindowingMode(windowingMode);
2302 } finally {
2303 Binder.restoreCallingIdentity(ident);
2304 }
2305 }
2306 }
2307
2308 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002310 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 ActivityRecord r = getCallingRecordLocked(token);
2312 return r != null ? r.info.packageName : null;
2313 }
2314 }
2315
2316 @Override
2317 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 ActivityRecord r = getCallingRecordLocked(token);
2320 return r != null ? r.intent.getComponent() : null;
2321 }
2322 }
2323
2324 private ActivityRecord getCallingRecordLocked(IBinder token) {
2325 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2326 if (r == null) {
2327 return null;
2328 }
2329 return r.resultTo;
2330 }
2331
2332 @Override
2333 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002334 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002335
2336 synchronized (mGlobalLock) {
2337 final long origId = Binder.clearCallingIdentity();
2338 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002339 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002340 } finally {
2341 Binder.restoreCallingIdentity(origId);
2342 }
2343 }
2344 }
2345
Mark Renouf446251d2019-04-26 10:22:41 -04002346 @Override
2347 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2348 synchronized (mGlobalLock) {
2349 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2350 if (r == null) {
2351 return;
2352 }
2353 ActivityStack stack = r.getActivityStack();
2354 if (stack != null && stack.isSingleTaskInstance()) {
2355 // Single-task stacks are used for activities which are presented in floating
2356 // windows above full screen activities. Instead of directly finishing the
2357 // task, a task change listener is used to notify SystemUI so the action can be
2358 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002359 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002360 mTaskChangeNotificationController
2361 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2362 } else {
2363 try {
2364 callback.requestFinish();
2365 } catch (RemoteException e) {
2366 Slog.e(TAG, "Failed to invoke request finish callback", e);
2367 }
2368 }
2369 }
2370 }
2371
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 /**
2373 * TODO: Add mController hook
2374 */
2375 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002376 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2377 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002378 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002379
2380 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2381 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002382 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2383 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 }
2385 }
2386
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2388 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002390
Ricky Waiaca8a772019-04-04 16:01:06 +01002391 final int callingPid = Binder.getCallingPid();
2392 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002393 if (!isSameApp(callingUid, callingPackage)) {
2394 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2395 + Binder.getCallingPid() + " as package " + callingPackage;
2396 Slog.w(TAG, msg);
2397 throw new SecurityException(msg);
2398 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002399 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 SafeActivityOptions.abort(options);
2401 return;
2402 }
2403 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002404 WindowProcessController callerApp = null;
2405 if (appThread != null) {
2406 callerApp = getProcessController(appThread);
2407 }
2408 final ActivityStarter starter = getActivityStartController().obtainStarter(
2409 null /* intent */, "moveTaskToFront");
2410 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2411 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002412 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002413 return;
2414 }
2415 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002416 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002417 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002418 if (task == null) {
2419 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002420 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002421 return;
2422 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002423 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002425 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002426 return;
2427 }
2428 ActivityOptions realOptions = options != null
2429 ? options.getOptions(mStackSupervisor)
2430 : null;
2431 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2432 false /* forceNonResizable */);
2433
Wale Ogunwale21e06482019-11-18 05:14:15 -08002434 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002435 if (topActivity != null) {
2436
2437 // We are reshowing a task, use a starting window to hide the initial draw delay
2438 // so the transition can start earlier.
2439 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2440 true /* taskSwitch */, fromRecents);
2441 }
2442 } finally {
2443 Binder.restoreCallingIdentity(origId);
2444 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002445 }
2446
Ricky Waiaca8a772019-04-04 16:01:06 +01002447 /**
2448 * Return true if callingUid is system, or packageName belongs to that callingUid.
2449 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002450 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002451 try {
2452 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2453 if (packageName == null) {
2454 return false;
2455 }
2456 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2457 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2458 UserHandle.getUserId(callingUid));
2459 return UserHandle.isSameApp(callingUid, uid);
2460 }
2461 } catch (RemoteException e) {
2462 // Should not happen
2463 }
2464 return true;
2465 }
2466
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002467 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2468 int callingPid, int callingUid, String name) {
2469 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2470 return true;
2471 }
2472
2473 if (getRecentTasks().isCallerRecents(sourceUid)) {
2474 return true;
2475 }
2476
2477 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2478 if (perm == PackageManager.PERMISSION_GRANTED) {
2479 return true;
2480 }
2481 if (checkAllowAppSwitchUid(sourceUid)) {
2482 return true;
2483 }
2484
2485 // If the actual IPC caller is different from the logical source, then
2486 // also see if they are allowed to control app switches.
2487 if (callingUid != -1 && callingUid != sourceUid) {
2488 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2489 if (perm == PackageManager.PERMISSION_GRANTED) {
2490 return true;
2491 }
2492 if (checkAllowAppSwitchUid(callingUid)) {
2493 return true;
2494 }
2495 }
2496
2497 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2498 return false;
2499 }
2500
2501 private boolean checkAllowAppSwitchUid(int uid) {
2502 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2503 if (types != null) {
2504 for (int i = types.size() - 1; i >= 0; i--) {
2505 if (types.valueAt(i).intValue() == uid) {
2506 return true;
2507 }
2508 }
2509 }
2510 return false;
2511 }
2512
2513 @Override
2514 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2515 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2516 "setActivityController()");
2517 synchronized (mGlobalLock) {
2518 mController = controller;
2519 mControllerIsAMonkey = imAMonkey;
2520 Watchdog.getInstance().setActivityController(controller);
2521 }
2522 }
2523
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002524 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002525 synchronized (mGlobalLock) {
2526 return mController != null && mControllerIsAMonkey;
2527 }
2528 }
2529
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 @Override
2531 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2532 synchronized (mGlobalLock) {
2533 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2534 }
2535 }
2536
2537 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002538 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2539 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2540 }
2541
2542 @Override
2543 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2544 @WindowConfiguration.ActivityType int ignoreActivityType,
2545 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2546 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002547 final int callingPid = Binder.getCallingPid();
2548 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002549 final int[] profileIds = getUserManager().getProfileIds(
2550 UserHandle.getUserId(callingUid), true);
2551 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2552 for (int i = 0; i < profileIds.length; i++) {
2553 callingProfileIds.add(profileIds[i]);
2554 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2556
2557 synchronized (mGlobalLock) {
2558 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2559
Nicholas Sauer0259e532019-08-30 08:24:55 -07002560 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002561 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002562 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 }
2564
2565 return list;
2566 }
2567
2568 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002569 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2570 synchronized (mGlobalLock) {
2571 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002572 try {
2573 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2574 if (r == null) return;
2575
2576 final PooledConsumer c = PooledLambda.obtainConsumer(
2577 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2578 r, resultWho, requestCode);
2579 // TODO: This should probably only loop over the task since you need to be in the
2580 // same task to return results.
2581 r.getActivityStack().forAllActivities(c);
2582 c.recycle();
2583
2584 updateOomAdj();
2585 } finally {
2586 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002587 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002588 }
2589 }
2590
2591 @Override
2592 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002594 ActivityStack stack = ActivityRecord.getStackLocked(token);
2595 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002596 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002597 }
2598 return false;
2599 }
2600 }
2601
2602 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002603 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002604 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 synchronized (mGlobalLock) {
2606 final long ident = Binder.clearCallingIdentity();
2607 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002608 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609 if (task == null) {
2610 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2611 return;
2612 }
2613
2614 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2615 + " to stackId=" + stackId + " toTop=" + toTop);
2616
Louis Chang149d5c82019-12-30 09:47:39 +08002617 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002618 if (stack == null) {
2619 throw new IllegalStateException(
2620 "moveTaskToStack: No stack for stackId=" + stackId);
2621 }
2622 if (!stack.isActivityTypeStandardOrUndefined()) {
2623 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2624 + taskId + " to stack " + stackId);
2625 }
2626 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002627 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2629 }
2630 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2631 "moveTaskToStack");
2632 } finally {
2633 Binder.restoreCallingIdentity(ident);
2634 }
2635 }
2636 }
2637
2638 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002639 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2640 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002641
2642 final long ident = Binder.clearCallingIdentity();
2643 try {
2644 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002645 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002646 if (stack == null) {
2647 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2648 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002649 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002650 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2651 throw new IllegalArgumentException("Stack: " + stackId
2652 + " doesn't support animated resize.");
2653 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002654 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002655 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002656 }
2657 } finally {
2658 Binder.restoreCallingIdentity(ident);
2659 }
2660 }
2661
wilsonshih5c4cf522019-01-25 09:03:47 +08002662 @Override
2663 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2664 int animationDuration) {
2665 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2666
2667 final long ident = Binder.clearCallingIdentity();
2668 try {
2669 synchronized (mGlobalLock) {
2670 if (xOffset == 0 && yOffset == 0) {
2671 return;
2672 }
Louis Chang149d5c82019-12-30 09:47:39 +08002673 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002674 if (stack == null) {
2675 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2676 return;
2677 }
2678 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2679 throw new IllegalArgumentException("Stack: " + stackId
2680 + " doesn't support animated resize.");
2681 }
2682 final Rect destBounds = new Rect();
2683 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002684 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002685 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2686 return;
2687 }
2688 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002689 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002690 animationDuration, false /* fromFullscreen */);
2691 }
2692 } finally {
2693 Binder.restoreCallingIdentity(ident);
2694 }
2695 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 /**
2697 * Moves the specified task to the primary-split-screen stack.
2698 *
2699 * @param taskId Id of task to move.
2700 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2701 * exist already. See
2702 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2703 * and
2704 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2705 * @param toTop If the task and stack should be moved to the top.
2706 * @param animate Whether we should play an animation for the moving the task.
2707 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2708 * stack. Pass {@code null} to use default bounds.
2709 * @param showRecents If the recents activity should be shown on the other side of the task
2710 * going into split-screen mode.
2711 */
2712 @Override
2713 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2714 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002715 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002716 "setTaskWindowingModeSplitScreenPrimary()");
2717 synchronized (mGlobalLock) {
2718 final long ident = Binder.clearCallingIdentity();
2719 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002720 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002721 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002722 if (task == null) {
2723 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2724 return false;
2725 }
2726 if (DEBUG_STACK) Slog.d(TAG_STACK,
2727 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2728 + " to createMode=" + createMode + " toTop=" + toTop);
2729 if (!task.isActivityTypeStandardOrUndefined()) {
2730 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2731 + " non-standard task " + taskId + " to split-screen windowing mode");
2732 }
2733
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002734 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002735 final int windowingMode = task.getWindowingMode();
2736 final ActivityStack stack = task.getStack();
2737 if (toTop) {
2738 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2739 }
2740 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002741 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2742 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002743 return windowingMode != task.getWindowingMode();
2744 } finally {
2745 Binder.restoreCallingIdentity(ident);
2746 }
2747 }
2748 }
2749
2750 /**
2751 * Removes stacks in the input windowing modes from the system if they are of activity type
2752 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2753 */
2754 @Override
2755 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002757 "removeStacksInWindowingModes()");
2758
2759 synchronized (mGlobalLock) {
2760 final long ident = Binder.clearCallingIdentity();
2761 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002762 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002763 } finally {
2764 Binder.restoreCallingIdentity(ident);
2765 }
2766 }
2767 }
2768
2769 @Override
2770 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002771 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002772 "removeStacksWithActivityTypes()");
2773
2774 synchronized (mGlobalLock) {
2775 final long ident = Binder.clearCallingIdentity();
2776 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002777 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783
2784 @Override
2785 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2786 int userId) {
2787 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2789 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002791 final boolean detailed = checkGetTasksPermission(
2792 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2793 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 == PackageManager.PERMISSION_GRANTED;
2795
2796 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002797 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 callingUid);
2799 }
2800 }
2801
2802 @Override
2803 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002804 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002805 long ident = Binder.clearCallingIdentity();
2806 try {
2807 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002808 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 } finally {
2811 Binder.restoreCallingIdentity(ident);
2812 }
2813 }
2814
2815 @Override
2816 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002817 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 long ident = Binder.clearCallingIdentity();
2819 try {
2820 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002821 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 }
2823 } finally {
2824 Binder.restoreCallingIdentity(ident);
2825 }
2826 }
2827
2828 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002829 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2830 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2831 long ident = Binder.clearCallingIdentity();
2832 try {
2833 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002834 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002835 }
2836 } finally {
2837 Binder.restoreCallingIdentity(ident);
2838 }
2839 }
2840
2841 @Override
2842 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2843 int displayId) {
2844 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2845 long ident = Binder.clearCallingIdentity();
2846 try {
2847 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002848 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002849 }
2850 } finally {
2851 Binder.restoreCallingIdentity(ident);
2852 }
2853 }
2854
2855 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002857 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002858 final long callingUid = Binder.getCallingUid();
2859 final long origId = Binder.clearCallingIdentity();
2860 try {
2861 synchronized (mGlobalLock) {
2862 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002863 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2865 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2866 }
2867 } finally {
2868 Binder.restoreCallingIdentity(origId);
2869 }
2870 }
2871
2872 @Override
2873 public void startLockTaskModeByToken(IBinder token) {
2874 synchronized (mGlobalLock) {
2875 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2876 if (r == null) {
2877 return;
2878 }
Louis Changcdec0802019-11-11 11:45:07 +08002879 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 }
2881 }
2882
2883 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002884 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002885 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002886 // This makes inner call to look as if it was initiated by system.
2887 long ident = Binder.clearCallingIdentity();
2888 try {
2889 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002890 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002891 MATCH_TASK_IN_STACKS_ONLY);
2892 if (task == null) {
2893 return;
2894 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002895
2896 // When starting lock task mode the stack must be in front and focused
2897 task.getStack().moveToFront("startSystemLockTaskMode");
2898 startLockTaskModeLocked(task, true /* isSystemCaller */);
2899 }
2900 } finally {
2901 Binder.restoreCallingIdentity(ident);
2902 }
2903 }
2904
2905 @Override
2906 public void stopLockTaskModeByToken(IBinder token) {
2907 synchronized (mGlobalLock) {
2908 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2909 if (r == null) {
2910 return;
2911 }
Louis Changcdec0802019-11-11 11:45:07 +08002912 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002913 }
2914 }
2915
2916 /**
2917 * This API should be called by SystemUI only when user perform certain action to dismiss
2918 * lock task mode. We should only dismiss pinned lock task mode in this case.
2919 */
2920 @Override
2921 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002922 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2924 }
2925
Louis Changcdec0802019-11-11 11:45:07 +08002926 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2928 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2929 return;
2930 }
2931
Louis Chang149d5c82019-12-30 09:47:39 +08002932 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002933 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934 throw new IllegalArgumentException("Invalid task, not in foreground");
2935 }
2936
2937 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2938 // system or a specific app.
2939 // * System-initiated requests will only start the pinned mode (screen pinning)
2940 // * App-initiated requests
2941 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2942 // - will start the pinned mode, otherwise
2943 final int callingUid = Binder.getCallingUid();
2944 long ident = Binder.clearCallingIdentity();
2945 try {
2946 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002947 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002949 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 } finally {
2951 Binder.restoreCallingIdentity(ident);
2952 }
2953 }
2954
Louis Changcdec0802019-11-11 11:45:07 +08002955 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 final int callingUid = Binder.getCallingUid();
2957 long ident = Binder.clearCallingIdentity();
2958 try {
2959 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002960 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 }
2962 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2963 // task and jumping straight into a call in the case of emergency call back.
2964 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2965 if (tm != null) {
2966 tm.showInCallScreen(false);
2967 }
2968 } finally {
2969 Binder.restoreCallingIdentity(ident);
2970 }
2971 }
2972
2973 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002974 public void updateLockTaskPackages(int userId, String[] packages) {
2975 final int callingUid = Binder.getCallingUid();
2976 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2977 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2978 "updateLockTaskPackages()");
2979 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002980 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002981 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2982 + Arrays.toString(packages));
2983 getLockTaskController().updateLockTaskPackages(userId, packages);
2984 }
2985 }
2986
2987 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 public boolean isInLockTaskMode() {
2989 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2990 }
2991
2992 @Override
2993 public int getLockTaskModeState() {
2994 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002995 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 }
2997 }
2998
2999 @Override
3000 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3001 synchronized (mGlobalLock) {
3002 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3003 if (r != null) {
3004 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003005 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003007 }
3008 }
3009 }
3010
3011 @Override
3012 public Bundle getActivityOptions(IBinder token) {
3013 final long origId = Binder.clearCallingIdentity();
3014 try {
3015 synchronized (mGlobalLock) {
3016 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3017 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003018 final ActivityOptions activityOptions = r.takeOptionsLocked(
3019 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 return activityOptions == null ? null : activityOptions.toBundle();
3021 }
3022 return null;
3023 }
3024 } finally {
3025 Binder.restoreCallingIdentity(origId);
3026 }
3027 }
3028
3029 @Override
3030 public List<IBinder> getAppTasks(String callingPackage) {
3031 int callingUid = Binder.getCallingUid();
3032 long ident = Binder.clearCallingIdentity();
3033 try {
3034 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003035 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 }
3037 } finally {
3038 Binder.restoreCallingIdentity(ident);
3039 }
3040 }
3041
3042 @Override
3043 public void finishVoiceTask(IVoiceInteractionSession session) {
3044 synchronized (mGlobalLock) {
3045 final long origId = Binder.clearCallingIdentity();
3046 try {
3047 // TODO: VI Consider treating local voice interactions and voice tasks
3048 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003049 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 } finally {
3051 Binder.restoreCallingIdentity(origId);
3052 }
3053 }
3054
3055 }
3056
3057 @Override
3058 public boolean isTopOfTask(IBinder token) {
3059 synchronized (mGlobalLock) {
3060 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003061 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 }
3063 }
3064
3065 @Override
3066 public void notifyLaunchTaskBehindComplete(IBinder token) {
3067 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3068 }
3069
3070 @Override
3071 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003072 mH.post(() -> {
3073 synchronized (mGlobalLock) {
3074 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003075 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003076 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003077 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003078 } catch (RemoteException e) {
3079 }
3080 }
3081 }
3082
3083 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084 }
3085
3086 /** Called from an app when assist data is ready. */
3087 @Override
3088 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3089 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003090 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 synchronized (pae) {
3092 pae.result = extras;
3093 pae.structure = structure;
3094 pae.content = content;
3095 if (referrer != null) {
3096 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3097 }
3098 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003099 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003100 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003101 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 structure.setHomeActivity(pae.isHome);
3103 }
3104 pae.haveResult = true;
3105 pae.notifyAll();
3106 if (pae.intent == null && pae.receiver == null) {
3107 // Caller is just waiting for the result.
3108 return;
3109 }
3110 }
3111 // We are now ready to launch the assist activity.
3112 IAssistDataReceiver sendReceiver = null;
3113 Bundle sendBundle = null;
3114 synchronized (mGlobalLock) {
3115 buildAssistBundleLocked(pae, extras);
3116 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003117 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 if (!exists) {
3119 // Timed out.
3120 return;
3121 }
3122
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003123 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 // Caller wants result sent back to them.
3125 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003126 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003127 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003128 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3129 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003130 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3131 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3132 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3133 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3134 }
3135 }
3136 if (sendReceiver != null) {
3137 try {
3138 sendReceiver.onHandleAssistData(sendBundle);
3139 } catch (RemoteException e) {
3140 }
3141 return;
3142 }
3143
3144 final long ident = Binder.clearCallingIdentity();
3145 try {
3146 if (TextUtils.equals(pae.intent.getAction(),
3147 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003148 // Start voice interaction through VoiceInteractionManagerService.
3149 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3150 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 } else {
3152 pae.intent.replaceExtras(pae.extras);
3153 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3154 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3155 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003156 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157
3158 try {
3159 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3160 } catch (ActivityNotFoundException e) {
3161 Slog.w(TAG, "No activity to handle assist action.", e);
3162 }
3163 }
3164 } finally {
3165 Binder.restoreCallingIdentity(ident);
3166 }
3167 }
3168
3169 @Override
3170 public int addAppTask(IBinder activityToken, Intent intent,
3171 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3172 final int callingUid = Binder.getCallingUid();
3173 final long callingIdent = Binder.clearCallingIdentity();
3174
3175 try {
3176 synchronized (mGlobalLock) {
3177 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3178 if (r == null) {
3179 throw new IllegalArgumentException("Activity does not exist; token="
3180 + activityToken);
3181 }
3182 ComponentName comp = intent.getComponent();
3183 if (comp == null) {
3184 throw new IllegalArgumentException("Intent " + intent
3185 + " must specify explicit component");
3186 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003187 if (thumbnail.getWidth() != mThumbnailWidth
3188 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 throw new IllegalArgumentException("Bad thumbnail size: got "
3190 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003191 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 }
3193 if (intent.getSelector() != null) {
3194 intent.setSelector(null);
3195 }
3196 if (intent.getSourceBounds() != null) {
3197 intent.setSourceBounds(null);
3198 }
3199 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3200 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3201 // The caller has added this as an auto-remove task... that makes no
3202 // sense, so turn off auto-remove.
3203 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3204 }
3205 }
3206 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3207 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3208 if (ainfo.applicationInfo.uid != callingUid) {
3209 throw new SecurityException(
3210 "Can't add task for another application: target uid="
3211 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3212 }
3213
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003214 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003215 final Task task = stack.createTask(
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08003216 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003218 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003219 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003220 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003221 return INVALID_TASK_ID;
3222 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003223 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224
3225 // TODO: Send the thumbnail to WM to store it.
3226
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003227 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003228 }
3229 } finally {
3230 Binder.restoreCallingIdentity(callingIdent);
3231 }
3232 }
3233
3234 @Override
3235 public Point getAppTaskThumbnailSize() {
3236 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003237 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 }
3239 }
3240
3241 @Override
3242 public void setTaskResizeable(int taskId, int resizeableMode) {
3243 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003244 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3246 if (task == null) {
3247 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3248 return;
3249 }
3250 task.setResizeMode(resizeableMode);
3251 }
3252 }
3253
3254 @Override
3255 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003256 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003257 long ident = Binder.clearCallingIdentity();
3258 try {
3259 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003260 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003261 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003262 if (task == null) {
3263 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3264 return;
3265 }
3266 // Place the task in the right stack if it isn't there already based on
3267 // the requested bounds.
3268 // The stack transition logic is:
3269 // - a null bounds on a freeform task moves that task to fullscreen
3270 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3271 // that task to freeform
3272 // - otherwise the task is not moved
3273 ActivityStack stack = task.getStack();
3274 if (!task.getWindowConfiguration().canResizeTask()) {
3275 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3276 }
3277 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3278 stack = stack.getDisplay().getOrCreateStack(
3279 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3280 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3281 stack = stack.getDisplay().getOrCreateStack(
3282 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3283 }
3284
3285 // Reparent the task to the right stack if necessary
3286 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3287 if (stack != task.getStack()) {
3288 // Defer resume until the task is resized below
3289 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3290 DEFER_RESUME, "resizeTask");
3291 preserveWindow = false;
3292 }
3293
3294 // After reparenting (which only resizes the task to the stack bounds), resize the
3295 // task to the actual bounds provided
3296 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3297 }
3298 } finally {
3299 Binder.restoreCallingIdentity(ident);
3300 }
3301 }
3302
Evan Roskyddedfd42019-10-04 13:38:38 -07003303 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3304 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003305 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003306 throw new RuntimeException("Invalid token in task transaction");
3307 }
3308 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3309 // masks here.
3310 int configMask = change.getConfigSetMask();
3311 int windowMask = change.getWindowSetMask();
3312 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3313 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3314 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3315 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3316 c.setTo(change.getConfiguration(), configMask, windowMask);
3317 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003318 // TODO(b/145675353): remove the following once we could apply new bounds to the
3319 // pinned stack together with its children.
3320 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3321 }
3322
3323 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3324 int windowMask, Configuration config) {
3325 if ((container instanceof ActivityStack)
3326 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3327 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3328 final ActivityStack stack = (ActivityStack) container;
3329 if (stack.inPinnedWindowingMode()) {
3330 stack.resize(config.windowConfiguration.getBounds(),
3331 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3332 PRESERVE_WINDOWS, true /* deferResume */);
3333 }
3334 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003335 }
3336
Robert Carr8a2f9132019-11-11 15:03:15 -08003337 private void applyWindowContainerChange(ConfigurationContainer cc,
3338 WindowContainerTransaction.Change c) {
3339 sanitizeAndApplyConfigChange(cc, c);
3340
3341 Rect enterPipBounds = c.getEnterPipBounds();
3342 if (enterPipBounds != null) {
3343 Task tr = (Task) cc;
3344 mStackSupervisor.updatePictureInPictureMode(tr,
3345 enterPipBounds, true);
3346 }
3347 }
3348
Evan Roskyddedfd42019-10-04 13:38:38 -07003349 @Override
3350 public void applyContainerTransaction(WindowContainerTransaction t) {
3351 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3352 long ident = Binder.clearCallingIdentity();
3353 try {
3354 if (t == null) {
3355 return;
3356 }
3357 synchronized (mGlobalLock) {
3358 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3359 t.getChanges().entrySet().iterator();
3360 while (entries.hasNext()) {
3361 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3362 entries.next();
3363 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3364 entry.getKey()).getContainer();
Robert Carr8a2f9132019-11-11 15:03:15 -08003365 applyWindowContainerChange(cc, entry.getValue());
Evan Roskyddedfd42019-10-04 13:38:38 -07003366 }
3367 }
3368 } finally {
3369 Binder.restoreCallingIdentity(ident);
3370 }
3371 }
3372
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373 @Override
3374 public boolean releaseActivityInstance(IBinder token) {
3375 synchronized (mGlobalLock) {
3376 final long origId = Binder.clearCallingIdentity();
3377 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003378 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3379 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 return false;
3381 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003382 r.destroyImmediately(true /* removeFromApp */, "app-req");
3383 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003384 } finally {
3385 Binder.restoreCallingIdentity(origId);
3386 }
3387 }
3388 }
3389
3390 @Override
3391 public void releaseSomeActivities(IApplicationThread appInt) {
3392 synchronized (mGlobalLock) {
3393 final long origId = Binder.clearCallingIdentity();
3394 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003395 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003396 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 } finally {
3398 Binder.restoreCallingIdentity(origId);
3399 }
3400 }
3401 }
3402
3403 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003404 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003405 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 != PackageManager.PERMISSION_GRANTED) {
3407 throw new SecurityException("Requires permission "
3408 + android.Manifest.permission.DEVICE_POWER);
3409 }
3410
3411 synchronized (mGlobalLock) {
3412 long ident = Binder.clearCallingIdentity();
3413 if (mKeyguardShown != keyguardShowing) {
3414 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003415 final Message msg = PooledLambda.obtainMessage(
3416 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3417 keyguardShowing);
3418 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 }
3420 try {
wilsonshih177261f2019-02-22 12:02:18 +08003421 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 } finally {
3423 Binder.restoreCallingIdentity(ident);
3424 }
3425 }
3426
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003427 mH.post(() -> {
3428 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3429 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3430 }
3431 });
3432 }
3433
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003434 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003435 mH.post(() -> {
3436 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3437 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3438 }
3439 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 }
3441
3442 @Override
3443 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003444 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3445 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446
3447 final File passedIconFile = new File(filePath);
3448 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3449 passedIconFile.getName());
3450 if (!legitIconFile.getPath().equals(filePath)
3451 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3452 throw new IllegalArgumentException("Bad file path: " + filePath
3453 + " passed for userId " + userId);
3454 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003455 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 }
3457
3458 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003460 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003461 synchronized (mGlobalLock) {
3462 final long ident = Binder.clearCallingIdentity();
3463 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003464 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 if (stack == null) {
3466 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3467 return;
3468 }
3469 if (!stack.isActivityTypeStandardOrUndefined()) {
3470 throw new IllegalArgumentException(
3471 "Removing non-standard stack is not allowed.");
3472 }
3473 mStackSupervisor.removeStack(stack);
3474 } finally {
3475 Binder.restoreCallingIdentity(ident);
3476 }
3477 }
3478 }
3479
3480 @Override
3481 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003482 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483
3484 synchronized (mGlobalLock) {
3485 final long ident = Binder.clearCallingIdentity();
3486 try {
3487 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3488 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003489 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490 } finally {
3491 Binder.restoreCallingIdentity(ident);
3492 }
3493 }
3494 }
3495
3496 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003497 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003498 synchronized (mGlobalLock) {
3499 long ident = Binder.clearCallingIdentity();
3500 try {
3501 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3502 if (r == null) {
3503 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003504 "toggleFreeformWindowingMode: No activity record matching token="
3505 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 }
3507
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003508 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003509 if (stack == null) {
3510 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3511 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 }
3513
Yunfan Chend967af82019-01-17 18:30:18 +09003514 if (!stack.inFreeformWindowingMode()
3515 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3516 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3517 + "toggle between fullscreen and freeform.");
3518 }
3519
3520 if (stack.inFreeformWindowingMode()) {
3521 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003522 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003523 throw new IllegalStateException("Size-compat windows are currently not"
3524 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003525 } else if (stack.getParent().inFreeformWindowingMode()) {
3526 // If the window is on a freeform display, set it to undefined. It will be
3527 // resolved to freeform and it can adjust windowing mode when the display mode
3528 // changes in runtime.
3529 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003530 } else {
3531 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3532 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003533 } finally {
3534 Binder.restoreCallingIdentity(ident);
3535 }
3536 }
3537 }
3538
3539 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3540 @Override
3541 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003542 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003543 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003544 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545 }
3546
3547 /** Unregister a task stack listener so that it stops receiving callbacks. */
3548 @Override
3549 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003550 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003552 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003553 }
3554
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 @Override
3556 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3557 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3558 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3559 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3560 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3561 }
3562
3563 @Override
3564 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3565 IBinder activityToken, int flags) {
3566 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3567 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3568 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3569 }
3570
3571 @Override
3572 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3573 Bundle args) {
3574 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3575 true /* focused */, true /* newSessionId */, userHandle, args,
3576 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3577 }
3578
3579 @Override
3580 public Bundle getAssistContextExtras(int requestType) {
3581 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3582 null, null, true /* focused */, true /* newSessionId */,
3583 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3584 if (pae == null) {
3585 return null;
3586 }
3587 synchronized (pae) {
3588 while (!pae.haveResult) {
3589 try {
3590 pae.wait();
3591 } catch (InterruptedException e) {
3592 }
3593 }
3594 }
3595 synchronized (mGlobalLock) {
3596 buildAssistBundleLocked(pae, pae.result);
3597 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003598 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 }
3600 return pae.extras;
3601 }
3602
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003603 /**
3604 * Binder IPC calls go through the public entry point.
3605 * This can be called with or without the global lock held.
3606 */
3607 private static int checkCallingPermission(String permission) {
3608 return checkPermission(
3609 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3610 }
3611
3612 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003613 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003614 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3615 mAmInternal.enforceCallingPermission(permission, func);
3616 }
3617 }
3618
3619 @VisibleForTesting
3620 int checkGetTasksPermission(String permission, int pid, int uid) {
3621 return checkPermission(permission, pid, uid);
3622 }
3623
3624 static int checkPermission(String permission, int pid, int uid) {
3625 if (permission == null) {
3626 return PackageManager.PERMISSION_DENIED;
3627 }
3628 return checkComponentPermission(permission, pid, uid, -1, true);
3629 }
3630
Wale Ogunwale214f3482018-10-04 11:00:47 -07003631 public static int checkComponentPermission(String permission, int pid, int uid,
3632 int owningUid, boolean exported) {
3633 return ActivityManagerService.checkComponentPermission(
3634 permission, pid, uid, owningUid, exported);
3635 }
3636
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003637 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3638 if (getRecentTasks().isCallerRecents(callingUid)) {
3639 // Always allow the recents component to get tasks
3640 return true;
3641 }
3642
3643 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3644 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3645 if (!allowed) {
3646 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3647 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3648 // Temporary compatibility: some existing apps on the system image may
3649 // still be requesting the old permission and not switched to the new
3650 // one; if so, we'll still allow them full access. This means we need
3651 // to see if they are holding the old permission and are a system app.
3652 try {
3653 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3654 allowed = true;
3655 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3656 + " is using old GET_TASKS but privileged; allowing");
3657 }
3658 } catch (RemoteException e) {
3659 }
3660 }
3661 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3662 + " does not hold REAL_GET_TASKS; limiting output");
3663 }
3664 return allowed;
3665 }
3666
Nicholas Sauer0259e532019-08-30 08:24:55 -07003667 boolean isCrossUserAllowed(int pid, int uid) {
3668 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3669 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3670 }
3671
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003672 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3673 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3674 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3675 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003676 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677 "enqueueAssistContext()");
3678
3679 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003680 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681 if (activity == null) {
3682 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3683 return null;
3684 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003685 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003686 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3687 return null;
3688 }
3689 if (focused) {
3690 if (activityToken != null) {
3691 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3692 if (activity != caller) {
3693 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3694 + " is not current top " + activity);
3695 return null;
3696 }
3697 }
3698 } else {
3699 activity = ActivityRecord.forTokenLocked(activityToken);
3700 if (activity == null) {
3701 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3702 + " couldn't be found");
3703 return null;
3704 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003705 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003706 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3707 return null;
3708 }
3709 }
3710
3711 PendingAssistExtras pae;
3712 Bundle extras = new Bundle();
3713 if (args != null) {
3714 extras.putAll(args);
3715 }
3716 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003717 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718
3719 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3720 userHandle);
3721 pae.isHome = activity.isActivityTypeHome();
3722
3723 // Increment the sessionId if necessary
3724 if (newSessionId) {
3725 mViSessionId++;
3726 }
3727 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003728 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3729 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003730 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003731 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003732 } catch (RemoteException e) {
3733 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3734 return null;
3735 }
3736 return pae;
3737 }
3738 }
3739
3740 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3741 if (result != null) {
3742 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3743 }
3744 if (pae.hint != null) {
3745 pae.extras.putBoolean(pae.hint, true);
3746 }
3747 }
3748
3749 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3750 IAssistDataReceiver receiver;
3751 synchronized (mGlobalLock) {
3752 mPendingAssistExtras.remove(pae);
3753 receiver = pae.receiver;
3754 }
3755 if (receiver != null) {
3756 // Caller wants result sent back to them.
3757 Bundle sendBundle = new Bundle();
3758 // At least return the receiver extras
3759 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3760 try {
3761 pae.receiver.onHandleAssistData(sendBundle);
3762 } catch (RemoteException e) {
3763 }
3764 }
3765 }
3766
3767 public class PendingAssistExtras extends Binder implements Runnable {
3768 public final ActivityRecord activity;
3769 public boolean isHome;
3770 public final Bundle extras;
3771 public final Intent intent;
3772 public final String hint;
3773 public final IAssistDataReceiver receiver;
3774 public final int userHandle;
3775 public boolean haveResult = false;
3776 public Bundle result = null;
3777 public AssistStructure structure = null;
3778 public AssistContent content = null;
3779 public Bundle receiverExtras;
3780
3781 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3782 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3783 int _userHandle) {
3784 activity = _activity;
3785 extras = _extras;
3786 intent = _intent;
3787 hint = _hint;
3788 receiver = _receiver;
3789 receiverExtras = _receiverExtras;
3790 userHandle = _userHandle;
3791 }
3792
3793 @Override
3794 public void run() {
3795 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3796 synchronized (this) {
3797 haveResult = true;
3798 notifyAll();
3799 }
3800 pendingAssistExtrasTimedOut(this);
3801 }
3802 }
3803
3804 @Override
3805 public boolean isAssistDataAllowedOnCurrentActivity() {
3806 int userId;
3807 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003808 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003809 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3810 return false;
3811 }
3812
Wale Ogunwale21e06482019-11-18 05:14:15 -08003813 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003814 if (activity == null) {
3815 return false;
3816 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003817 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003818 }
3819 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3820 }
3821
3822 @Override
3823 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3824 long ident = Binder.clearCallingIdentity();
3825 try {
3826 synchronized (mGlobalLock) {
3827 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003828 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 if (top != caller) {
3830 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3831 + " is not current top " + top);
3832 return false;
3833 }
3834 if (!top.nowVisible) {
3835 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3836 + " is not visible");
3837 return false;
3838 }
3839 }
3840 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3841 token);
3842 } finally {
3843 Binder.restoreCallingIdentity(ident);
3844 }
3845 }
3846
3847 @Override
3848 public boolean isRootVoiceInteraction(IBinder token) {
3849 synchronized (mGlobalLock) {
3850 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3851 if (r == null) {
3852 return false;
3853 }
3854 return r.rootVoiceInteraction;
3855 }
3856 }
3857
Wale Ogunwalef6733932018-06-27 05:14:34 -07003858 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3859 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3860 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3861 if (activityToCallback == null) return;
3862 activityToCallback.setVoiceSessionLocked(voiceSession);
3863
3864 // Inform the activity
3865 try {
3866 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3867 voiceInteractor);
3868 long token = Binder.clearCallingIdentity();
3869 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003870 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003871 } finally {
3872 Binder.restoreCallingIdentity(token);
3873 }
3874 // TODO: VI Should we cache the activity so that it's easier to find later
3875 // rather than scan through all the stacks and activities?
3876 } catch (RemoteException re) {
3877 activityToCallback.clearVoiceSessionLocked();
3878 // TODO: VI Should this terminate the voice session?
3879 }
3880 }
3881
3882 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3883 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3884 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3885 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3886 boolean wasRunningVoice = mRunningVoice != null;
3887 mRunningVoice = session;
3888 if (!wasRunningVoice) {
3889 mVoiceWakeLock.acquire();
3890 updateSleepIfNeededLocked();
3891 }
3892 }
3893 }
3894
3895 void finishRunningVoiceLocked() {
3896 if (mRunningVoice != null) {
3897 mRunningVoice = null;
3898 mVoiceWakeLock.release();
3899 updateSleepIfNeededLocked();
3900 }
3901 }
3902
3903 @Override
3904 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3905 synchronized (mGlobalLock) {
3906 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3907 if (keepAwake) {
3908 mVoiceWakeLock.acquire();
3909 } else {
3910 mVoiceWakeLock.release();
3911 }
3912 }
3913 }
3914 }
3915
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 @Override
3917 public ComponentName getActivityClassForToken(IBinder token) {
3918 synchronized (mGlobalLock) {
3919 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3920 if (r == null) {
3921 return null;
3922 }
3923 return r.intent.getComponent();
3924 }
3925 }
3926
3927 @Override
3928 public String getPackageForToken(IBinder token) {
3929 synchronized (mGlobalLock) {
3930 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3931 if (r == null) {
3932 return null;
3933 }
3934 return r.packageName;
3935 }
3936 }
3937
3938 @Override
3939 public void showLockTaskEscapeMessage(IBinder token) {
3940 synchronized (mGlobalLock) {
3941 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3942 if (r == null) {
3943 return;
3944 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003945 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 }
3947 }
3948
3949 @Override
3950 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003951 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 final long token = Binder.clearCallingIdentity();
3953 try {
3954 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003955 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 }
3957 } finally {
3958 Binder.restoreCallingIdentity(token);
3959 }
3960 }
3961
3962 /**
3963 * Try to place task to provided position. The final position might be different depending on
3964 * current user and stacks state. The task will be moved to target stack if it's currently in
3965 * different stack.
3966 */
3967 @Override
3968 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003969 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003970 synchronized (mGlobalLock) {
3971 long ident = Binder.clearCallingIdentity();
3972 try {
3973 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3974 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003975 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 if (task == null) {
3977 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3978 + taskId);
3979 }
3980
Louis Chang149d5c82019-12-30 09:47:39 +08003981 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982
3983 if (stack == null) {
3984 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3985 + stackId);
3986 }
3987 if (!stack.isActivityTypeStandardOrUndefined()) {
3988 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3989 + " the position of task " + taskId + " in/to non-standard stack");
3990 }
3991
3992 // TODO: Have the callers of this API call a separate reparent method if that is
3993 // what they intended to do vs. having this method also do reparenting.
3994 if (task.getStack() == stack) {
3995 // Change position in current stack.
3996 stack.positionChildAt(task, position);
3997 } else {
3998 // Reparent to new stack.
3999 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4000 !DEFER_RESUME, "positionTaskInStack");
4001 }
4002 } finally {
4003 Binder.restoreCallingIdentity(ident);
4004 }
4005 }
4006 }
4007
4008 @Override
4009 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4010 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4011 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004012 + Arrays.toString(horizontalSizeConfiguration) + " "
4013 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 synchronized (mGlobalLock) {
4015 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4016 if (record == null) {
4017 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4018 + "found for: " + token);
4019 }
4020 record.setSizeConfigurations(horizontalSizeConfiguration,
4021 verticalSizeConfigurations, smallestSizeConfigurations);
4022 }
4023 }
4024
4025 /**
4026 * Dismisses split-screen multi-window mode.
4027 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4028 */
4029 @Override
4030 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4033 final long ident = Binder.clearCallingIdentity();
4034 try {
4035 synchronized (mGlobalLock) {
4036 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004037 mRootWindowContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 if (stack == null) {
4039 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4040 return;
4041 }
4042
4043 if (toTop) {
4044 // Caller wants the current split-screen primary stack to be the top stack after
4045 // it goes fullscreen, so move it to the front.
4046 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004047 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004048 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004049 // stack after it goes fullscreen, so we move the focus to the top-most
4050 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4052 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4053 if (otherStack != null) {
4054 otherStack.moveToFront("dismissSplitScreenMode_other");
4055 }
4056 }
4057
Evan Rosky10475742018-09-05 19:02:48 -07004058 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 }
4060 } finally {
4061 Binder.restoreCallingIdentity(ident);
4062 }
4063 }
4064
4065 /**
4066 * Dismisses Pip
4067 * @param animate True if the dismissal should be animated.
4068 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4069 * default animation duration should be used.
4070 */
4071 @Override
4072 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004073 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 final long ident = Binder.clearCallingIdentity();
4075 try {
4076 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004077 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004078 mRootWindowContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 if (stack == null) {
4080 Slog.w(TAG, "dismissPip: pinned stack not found.");
4081 return;
4082 }
4083 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4084 throw new IllegalArgumentException("Stack: " + stack
4085 + " doesn't support animated resize.");
4086 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004087 /**
4088 * TODO(b/146594635): Remove all PIP animation code from WM
4089 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4090 */
4091 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004092 stack.animateResizePinnedStack(null /* destBounds */,
4093 null /* sourceHintBounds */, animationDuration,
4094 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004096 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004097 }
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(ident);
4101 }
4102 }
4103
4104 @Override
4105 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004106 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004107 synchronized (mGlobalLock) {
4108 mSuppressResizeConfigChanges = suppress;
4109 }
4110 }
4111
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004112 @Override
4113 // TODO: API should just be about changing windowing modes...
4114 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004115 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 "moveTasksToFullscreenStack()");
4117 synchronized (mGlobalLock) {
4118 final long origId = Binder.clearCallingIdentity();
4119 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004120 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 if (stack != null){
4122 if (!stack.isActivityTypeStandardOrUndefined()) {
4123 throw new IllegalArgumentException(
4124 "You can't move tasks from non-standard stacks.");
4125 }
4126 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4127 }
4128 } finally {
4129 Binder.restoreCallingIdentity(origId);
4130 }
4131 }
4132 }
4133
4134 /**
4135 * Moves the top activity in the input stackId to the pinned stack.
4136 *
4137 * @param stackId Id of stack to move the top activity to pinned stack.
4138 * @param bounds Bounds to use for pinned stack.
4139 *
4140 * @return True if the top activity of the input stack was successfully moved to the pinned
4141 * stack.
4142 */
4143 @Override
4144 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004145 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146 "moveTopActivityToPinnedStack()");
4147 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004148 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4150 + "Device doesn't support picture-in-picture mode");
4151 }
4152
4153 long ident = Binder.clearCallingIdentity();
4154 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004155 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004156 } finally {
4157 Binder.restoreCallingIdentity(ident);
4158 }
4159 }
4160 }
4161
4162 @Override
4163 public boolean isInMultiWindowMode(IBinder token) {
4164 final long origId = Binder.clearCallingIdentity();
4165 try {
4166 synchronized (mGlobalLock) {
4167 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4168 if (r == null) {
4169 return false;
4170 }
4171 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4172 return r.inMultiWindowMode();
4173 }
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177 }
4178
4179 @Override
4180 public boolean isInPictureInPictureMode(IBinder token) {
4181 final long origId = Binder.clearCallingIdentity();
4182 try {
4183 synchronized (mGlobalLock) {
4184 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4185 }
4186 } finally {
4187 Binder.restoreCallingIdentity(origId);
4188 }
4189 }
4190
4191 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004192 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4193 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004194 return false;
4195 }
4196
4197 // If we are animating to fullscreen then we have already dispatched the PIP mode
4198 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004199 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004200 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201 }
4202
4203 @Override
4204 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4205 final long origId = Binder.clearCallingIdentity();
4206 try {
4207 synchronized (mGlobalLock) {
4208 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4209 "enterPictureInPictureMode", token, params);
4210
4211 // If the activity is already in picture in picture mode, then just return early
4212 if (isInPictureInPictureMode(r)) {
4213 return true;
4214 }
4215
4216 // Activity supports picture-in-picture, now check that we can enter PiP at this
4217 // point, if it is
4218 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4219 false /* beforeStopping */)) {
4220 return false;
4221 }
4222
4223 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004224 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004225 if (r.getParent() == null) {
4226 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4227 return;
4228 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004229 // Only update the saved args from the args that are set
4230 r.pictureInPictureArgs.copyOnlySet(params);
4231 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4232 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4233 // Adjust the source bounds by the insets for the transition down
4234 final Rect sourceBounds = new Rect(
4235 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004236 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004237 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004238 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004239 stack.setPictureInPictureAspectRatio(aspectRatio);
4240 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004241 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4242 r.info.applicationInfo.uid, r.shortComponentName,
4243 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004244 logPictureInPictureArgs(params);
4245 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 };
4247
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004248 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 // If the keyguard is showing or occluded, then try and dismiss it before
4250 // entering picture-in-picture (this will prompt the user to authenticate if the
4251 // device is currently locked).
4252 dismissKeyguard(token, new KeyguardDismissCallback() {
4253 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004254 public void onDismissSucceeded() {
4255 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 }
4257 }, null /* message */);
4258 } else {
4259 // Enter picture in picture immediately otherwise
4260 enterPipRunnable.run();
4261 }
4262 return true;
4263 }
4264 } finally {
4265 Binder.restoreCallingIdentity(origId);
4266 }
4267 }
4268
4269 @Override
4270 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4271 final long origId = Binder.clearCallingIdentity();
4272 try {
4273 synchronized (mGlobalLock) {
4274 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4275 "setPictureInPictureParams", token, params);
4276
4277 // Only update the saved args from the args that are set
4278 r.pictureInPictureArgs.copyOnlySet(params);
4279 if (r.inPinnedWindowingMode()) {
4280 // If the activity is already in picture-in-picture, update the pinned stack now
4281 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4282 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004283 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004284 if (!stack.isAnimatingBoundsToFullscreen()) {
4285 stack.setPictureInPictureAspectRatio(
4286 r.pictureInPictureArgs.getAspectRatio());
4287 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4288 }
4289 }
4290 logPictureInPictureArgs(params);
4291 }
4292 } finally {
4293 Binder.restoreCallingIdentity(origId);
4294 }
4295 }
4296
4297 @Override
4298 public int getMaxNumPictureInPictureActions(IBinder token) {
4299 // Currently, this is a static constant, but later, we may change this to be dependent on
4300 // the context of the activity
4301 return 3;
4302 }
4303
4304 private void logPictureInPictureArgs(PictureInPictureParams params) {
4305 if (params.hasSetActions()) {
4306 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4307 params.getActions().size());
4308 }
4309 if (params.hasSetAspectRatio()) {
4310 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4311 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4312 MetricsLogger.action(lm);
4313 }
4314 }
4315
4316 /**
4317 * Checks the state of the system and the activity associated with the given {@param token} to
4318 * verify that picture-in-picture is supported for that activity.
4319 *
4320 * @return the activity record for the given {@param token} if all the checks pass.
4321 */
4322 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4323 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004324 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 throw new IllegalStateException(caller
4326 + ": Device doesn't support picture-in-picture mode.");
4327 }
4328
4329 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4330 if (r == null) {
4331 throw new IllegalStateException(caller
4332 + ": Can't find activity for token=" + token);
4333 }
4334
4335 if (!r.supportsPictureInPicture()) {
4336 throw new IllegalStateException(caller
4337 + ": Current activity does not support picture-in-picture.");
4338 }
4339
4340 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004341 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08004342 r.getDisplayId(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 final float minAspectRatio = mContext.getResources().getFloat(
4344 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4345 final float maxAspectRatio = mContext.getResources().getFloat(
4346 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4347 throw new IllegalArgumentException(String.format(caller
4348 + ": Aspect ratio is too extreme (must be between %f and %f).",
4349 minAspectRatio, maxAspectRatio));
4350 }
4351
4352 // Truncate the number of actions if necessary
4353 params.truncateActions(getMaxNumPictureInPictureActions(token));
4354
4355 return r;
4356 }
4357
4358 @Override
4359 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004360 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004361 synchronized (mGlobalLock) {
4362 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4363 if (r == null) {
4364 throw new IllegalArgumentException("Activity does not exist; token="
4365 + activityToken);
4366 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004367 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 }
4369 }
4370
4371 @Override
4372 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4373 Rect tempDockedTaskInsetBounds,
4374 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 long ident = Binder.clearCallingIdentity();
4377 try {
4378 synchronized (mGlobalLock) {
4379 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4380 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4381 PRESERVE_WINDOWS);
4382 }
4383 } finally {
4384 Binder.restoreCallingIdentity(ident);
4385 }
4386 }
4387
4388 @Override
4389 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 final long ident = Binder.clearCallingIdentity();
4392 try {
4393 synchronized (mGlobalLock) {
4394 mStackSupervisor.setSplitScreenResizing(resizing);
4395 }
4396 } finally {
4397 Binder.restoreCallingIdentity(ident);
4398 }
4399 }
4400
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004401 /**
4402 * Check that we have the features required for VR-related API calls, and throw an exception if
4403 * not.
4404 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004405 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 if (!mContext.getPackageManager().hasSystemFeature(
4407 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4408 throw new UnsupportedOperationException("VR mode not supported on this device!");
4409 }
4410 }
4411
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 @Override
4413 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415
4416 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4417
4418 ActivityRecord r;
4419 synchronized (mGlobalLock) {
4420 r = ActivityRecord.isInStackLocked(token);
4421 }
4422
4423 if (r == null) {
4424 throw new IllegalArgumentException();
4425 }
4426
4427 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004428 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 VrManagerInternal.NO_ERROR) {
4430 return err;
4431 }
4432
4433 // Clear the binder calling uid since this path may call moveToTask().
4434 final long callingId = Binder.clearCallingIdentity();
4435 try {
4436 synchronized (mGlobalLock) {
4437 r.requestedVrComponent = (enabled) ? packageName : null;
4438
4439 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004440 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004441 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 }
4443 return 0;
4444 }
4445 } finally {
4446 Binder.restoreCallingIdentity(callingId);
4447 }
4448 }
4449
4450 @Override
4451 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4452 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4453 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004454 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4456 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4457 }
Louis Changcdec0802019-11-11 11:45:07 +08004458 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004459 || activity.voiceSession != null) {
4460 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4461 return;
4462 }
4463 if (activity.pendingVoiceInteractionStart) {
4464 Slog.w(TAG, "Pending start of voice interaction already.");
4465 return;
4466 }
4467 activity.pendingVoiceInteractionStart = true;
4468 }
4469 LocalServices.getService(VoiceInteractionManagerInternal.class)
4470 .startLocalVoiceInteraction(callingActivity, options);
4471 }
4472
4473 @Override
4474 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4475 LocalServices.getService(VoiceInteractionManagerInternal.class)
4476 .stopLocalVoiceInteraction(callingActivity);
4477 }
4478
4479 @Override
4480 public boolean supportsLocalVoiceInteraction() {
4481 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4482 .supportsLocalVoiceInteraction();
4483 }
4484
4485 /** Notifies all listeners when the pinned stack animation starts. */
4486 @Override
4487 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004488 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 }
4490
4491 /** Notifies all listeners when the pinned stack animation ends. */
4492 @Override
4493 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004494 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 }
4496
4497 @Override
4498 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500 final long ident = Binder.clearCallingIdentity();
4501 try {
4502 synchronized (mGlobalLock) {
4503 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4504 }
4505 } finally {
4506 Binder.restoreCallingIdentity(ident);
4507 }
4508 }
4509
4510 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004512 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513
4514 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004515 if (mWindowManager == null) {
4516 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4517 return false;
4518 }
4519
4520 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 }
4524
Riddle Hsua0022cd2019-09-09 21:12:41 +08004525 mH.sendMessage(PooledLambda.obtainMessage(
4526 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4527 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004528
4529 final long origId = Binder.clearCallingIdentity();
4530 try {
4531 if (values != null) {
4532 Settings.System.clearConfiguration(values);
4533 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004534 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004535 UserHandle.USER_NULL, false /* deferResume */,
4536 mTmpUpdateConfigurationResult);
4537 return mTmpUpdateConfigurationResult.changes != 0;
4538 } finally {
4539 Binder.restoreCallingIdentity(origId);
4540 }
4541 }
4542 }
4543
4544 @Override
4545 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4546 CharSequence message) {
4547 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004548 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4550 }
4551 final long callingId = Binder.clearCallingIdentity();
4552 try {
4553 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004554 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004555 }
4556 } finally {
4557 Binder.restoreCallingIdentity(callingId);
4558 }
4559 }
4560
4561 @Override
4562 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004563 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 "cancelTaskWindowTransition()");
4565 final long ident = Binder.clearCallingIdentity();
4566 try {
4567 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004568 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 MATCH_TASK_IN_STACKS_ONLY);
4570 if (task == null) {
4571 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4572 return;
4573 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004574 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 }
4576 } finally {
4577 Binder.restoreCallingIdentity(ident);
4578 }
4579 }
4580
4581 @Override
4582 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004583 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004584 final long ident = Binder.clearCallingIdentity();
4585 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004586 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 } finally {
4588 Binder.restoreCallingIdentity(ident);
4589 }
4590 }
4591
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004592 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4593 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004594 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004595 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004596 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004597 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4598 if (task == null) {
4599 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4600 return null;
4601 }
4602 }
4603 // Don't call this while holding the lock as this operation might hit the disk.
4604 return task.getSnapshot(reducedResolution, restoreFromDisk);
4605 }
4606
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004607 @Override
4608 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4609 synchronized (mGlobalLock) {
4610 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4611 if (r == null) {
4612 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4613 + token);
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 r.setDisablePreviewScreenshots(disable);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
Riddle Hsu440f88b2019-11-06 22:17:35 +08004625 @Override
4626 public void invalidateHomeTaskSnapshot(IBinder token) {
4627 synchronized (mGlobalLock) {
4628 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4629 if (r == null || !r.isActivityTypeHome()) {
4630 return;
4631 }
4632 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4633 }
4634 }
4635
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004636 /** Return the user id of the last resumed activity. */
4637 @Override
4638 public @UserIdInt
4639 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004641 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4642 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004643 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004644 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004645 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004646 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004647 }
4648 }
4649
4650 @Override
4651 public void updateLockTaskFeatures(int userId, int flags) {
4652 final int callingUid = Binder.getCallingUid();
4653 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004655 "updateLockTaskFeatures()");
4656 }
4657 synchronized (mGlobalLock) {
4658 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4659 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004660 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004661 }
4662 }
4663
4664 @Override
4665 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
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.setShowWhenLocked(showWhenLocked);
4674 } finally {
4675 Binder.restoreCallingIdentity(origId);
4676 }
4677 }
4678 }
4679
4680 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004681 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4682 synchronized (mGlobalLock) {
4683 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4684 if (r == null) {
4685 return;
4686 }
4687 final long origId = Binder.clearCallingIdentity();
4688 try {
4689 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4690 } finally {
4691 Binder.restoreCallingIdentity(origId);
4692 }
4693 }
4694 }
4695
4696 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004697 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4698 synchronized (mGlobalLock) {
4699 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4700 if (r == null) {
4701 return;
4702 }
4703 final long origId = Binder.clearCallingIdentity();
4704 try {
4705 r.setTurnScreenOn(turnScreenOn);
4706 } finally {
4707 Binder.restoreCallingIdentity(origId);
4708 }
4709 }
4710 }
4711
4712 @Override
4713 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004715 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004716 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004717 synchronized (mGlobalLock) {
4718 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4719 if (r == null) {
4720 return;
4721 }
4722 final long origId = Binder.clearCallingIdentity();
4723 try {
4724 r.registerRemoteAnimations(definition);
4725 } finally {
4726 Binder.restoreCallingIdentity(origId);
4727 }
4728 }
4729 }
4730
4731 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004732 public void unregisterRemoteAnimations(IBinder token) {
4733 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4734 "unregisterRemoteAnimations");
4735 synchronized (mGlobalLock) {
4736 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4737 if (r == null) {
4738 return;
4739 }
4740 final long origId = Binder.clearCallingIdentity();
4741 try {
4742 r.unregisterRemoteAnimations();
4743 } finally {
4744 Binder.restoreCallingIdentity(origId);
4745 }
4746 }
4747 }
4748
4749 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004750 public void registerRemoteAnimationForNextActivityStart(String packageName,
4751 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004752 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004753 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004754 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004755 synchronized (mGlobalLock) {
4756 final long origId = Binder.clearCallingIdentity();
4757 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004758 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004759 packageName, adapter);
4760 } finally {
4761 Binder.restoreCallingIdentity(origId);
4762 }
4763 }
4764 }
4765
Evan Rosky966759f2019-01-15 10:33:58 -08004766 @Override
4767 public void registerRemoteAnimationsForDisplay(int displayId,
4768 RemoteAnimationDefinition definition) {
4769 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4770 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004771 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004772 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004773 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004774 if (display == null) {
4775 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4776 return;
4777 }
4778 final long origId = Binder.clearCallingIdentity();
4779 try {
4780 display.mDisplayContent.registerRemoteAnimations(definition);
4781 } finally {
4782 Binder.restoreCallingIdentity(origId);
4783 }
4784 }
4785 }
4786
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004787 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4788 @Override
4789 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4790 synchronized (mGlobalLock) {
4791 final long origId = Binder.clearCallingIdentity();
4792 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004793 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004794 } finally {
4795 Binder.restoreCallingIdentity(origId);
4796 }
4797 }
4798 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004799
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004800 @Override
4801 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004802 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004803 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004804 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004805 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004806 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004807 }
4808 }
4809
4810 @Override
4811 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004812 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004813 != PERMISSION_GRANTED) {
4814 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4815 + Binder.getCallingPid()
4816 + ", uid=" + Binder.getCallingUid()
4817 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4818 Slog.w(TAG, msg);
4819 throw new SecurityException(msg);
4820 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004821 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004822 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004823 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004824 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004825 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004826 }
4827 }
4828
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004829 @Override
4830 public void stopAppSwitches() {
4831 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4832 synchronized (mGlobalLock) {
4833 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004834 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004835 mDidAppSwitch = false;
4836 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4837 }
4838 }
4839
4840 @Override
4841 public void resumeAppSwitches() {
4842 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4843 synchronized (mGlobalLock) {
4844 // Note that we don't execute any pending app switches... we will
4845 // let those wait until either the timeout, or the next start
4846 // activity request.
4847 mAppSwitchesAllowedTime = 0;
4848 }
4849 }
4850
Ricky Wai906af482019-06-03 17:25:28 +01004851 long getLastStopAppSwitchesTime() {
4852 return mLastStopAppSwitchesTime;
4853 }
4854
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004855 void onStartActivitySetDidAppSwitch() {
4856 if (mDidAppSwitch) {
4857 // This is the second allowed switch since we stopped switches, so now just generally
4858 // allow switches. Use case:
4859 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4860 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4861 // anyone to switch again).
4862 mAppSwitchesAllowedTime = 0;
4863 } else {
4864 mDidAppSwitch = true;
4865 }
4866 }
4867
4868 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 boolean shouldDisableNonVrUiLocked() {
4870 return mVrController.shouldDisableNonVrUiLocked();
4871 }
4872
Wale Ogunwale53783742018-09-16 10:21:51 -07004873 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004874 // 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 +00004875 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004876 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004877 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4878 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004879 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004880 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004881 }
4882 mH.post(() -> {
4883 if (!mVrController.onVrModeChanged(r)) {
4884 return;
4885 }
4886 synchronized (mGlobalLock) {
4887 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4888 mWindowManager.disableNonVrUi(disableNonVrUi);
4889 if (disableNonVrUi) {
4890 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4891 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004892 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004893 }
4894 }
4895 });
4896 }
4897
Wale Ogunwale53783742018-09-16 10:21:51 -07004898 @Override
4899 public int getPackageScreenCompatMode(String packageName) {
4900 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4901 synchronized (mGlobalLock) {
4902 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4903 }
4904 }
4905
4906 @Override
4907 public void setPackageScreenCompatMode(String packageName, int mode) {
4908 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4909 "setPackageScreenCompatMode");
4910 synchronized (mGlobalLock) {
4911 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4912 }
4913 }
4914
4915 @Override
4916 public boolean getPackageAskScreenCompat(String packageName) {
4917 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4918 synchronized (mGlobalLock) {
4919 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4920 }
4921 }
4922
4923 @Override
4924 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4925 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4926 "setPackageAskScreenCompat");
4927 synchronized (mGlobalLock) {
4928 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4929 }
4930 }
4931
Wale Ogunwale64258362018-10-16 15:13:37 -07004932 public static String relaunchReasonToString(int relaunchReason) {
4933 switch (relaunchReason) {
4934 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4935 return "window_resize";
4936 case RELAUNCH_REASON_FREE_RESIZE:
4937 return "free_resize";
4938 default:
4939 return null;
4940 }
4941 }
4942
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004943 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004944 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004945 }
4946
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004947 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004948 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004949 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4950 }
4951
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004952 boolean isKeyguardLocked() {
4953 return mKeyguardController.isKeyguardLocked();
4954 }
4955
Garfield Tan01548632018-11-27 10:15:48 -08004956 /**
4957 * Clears launch params for the given package.
4958 * @param packageNames the names of the packages of which the launch params are to be cleared
4959 */
4960 @Override
4961 public void clearLaunchParamsForPackages(List<String> packageNames) {
4962 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4963 "clearLaunchParamsForPackages");
4964 synchronized (mGlobalLock) {
4965 for (int i = 0; i < packageNames.size(); ++i) {
4966 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4967 }
4968 }
4969 }
4970
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004971 /**
4972 * Makes the display with the given id a single task instance display. I.e the display can only
4973 * contain one task.
4974 */
4975 @Override
4976 public void setDisplayToSingleTaskInstance(int displayId) {
4977 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4978 "setDisplayToSingleTaskInstance");
4979 final long origId = Binder.clearCallingIdentity();
4980 try {
Louis Chang677921f2019-12-06 16:44:24 +08004981 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004982 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004983 if (display != null) {
4984 display.setDisplayToSingleTaskInstance();
4985 }
4986 } finally {
4987 Binder.restoreCallingIdentity(origId);
4988 }
4989 }
4990
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004991 /**
4992 * Requests that an activity should enter picture-in-picture mode if possible.
4993 */
4994 @Override
4995 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4996 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4997 "requestPictureInPictureMode");
4998 final long origId = Binder.clearCallingIdentity();
4999 try {
5000 synchronized (mGlobalLock) {
5001 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
5002 if (activity == null) {
5003 return;
5004 }
5005
5006 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
5007 "requestPictureInPictureMode", /* beforeStopping */ false);
5008 if (!canEnterPictureInPicture) {
5009 throw new IllegalStateException(
5010 "Requested PIP on an activity that doesn't support it");
5011 }
5012
5013 try {
5014 final ClientTransaction transaction = ClientTransaction.obtain(
5015 activity.app.getThread(),
5016 activity.token);
5017 transaction.addCallback(EnterPipRequestedItem.obtain());
5018 getLifecycleManager().scheduleTransaction(transaction);
5019 } catch (Exception e) {
5020 Slog.w(TAG, "Failed to send enter pip requested item: "
5021 + activity.intent.getComponent(), e);
5022 }
5023 }
5024 } finally {
5025 Binder.restoreCallingIdentity(origId);
5026 }
5027 }
5028
Wale Ogunwale31913b52018-10-13 08:29:31 -07005029 void dumpLastANRLocked(PrintWriter pw) {
5030 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5031 if (mLastANRState == null) {
5032 pw.println(" <no ANR has occurred since boot>");
5033 } else {
5034 pw.println(mLastANRState);
5035 }
5036 }
5037
5038 void dumpLastANRTracesLocked(PrintWriter pw) {
5039 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5040
5041 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5042 if (ArrayUtils.isEmpty(files)) {
5043 pw.println(" <no ANR has occurred since boot>");
5044 return;
5045 }
5046 // Find the latest file.
5047 File latest = null;
5048 for (File f : files) {
5049 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5050 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005051 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005052 }
5053 pw.print("File: ");
5054 pw.print(latest.getName());
5055 pw.println();
5056 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5057 String line;
5058 while ((line = in.readLine()) != null) {
5059 pw.println(line);
5060 }
5061 } catch (IOException e) {
5062 pw.print("Unable to read: ");
5063 pw.print(e);
5064 pw.println();
5065 }
5066 }
5067
5068 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5069 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5070 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5071 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5072 }
5073
5074 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5075 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5076 pw.println(header);
5077
Louis Chang149d5c82019-12-30 09:47:39 +08005078 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005079 dumpPackage);
5080 boolean needSep = printedAnything;
5081
5082 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005083 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005084 " ResumedActivity: ");
5085 if (printed) {
5086 printedAnything = true;
5087 needSep = false;
5088 }
5089
5090 if (dumpPackage == null) {
5091 if (needSep) {
5092 pw.println();
5093 }
5094 printedAnything = true;
5095 mStackSupervisor.dump(pw, " ");
5096 }
5097
5098 if (!printedAnything) {
5099 pw.println(" (nothing)");
5100 }
5101 }
5102
5103 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005104 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005105 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005106 pw.println(" ");
5107 }
5108
5109 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5110 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5111 getActivityStartController().dump(pw, "", dumpPackage);
5112 }
5113
5114 /**
5115 * There are three things that cmd can be:
5116 * - a flattened component name that matches an existing activity
5117 * - the cmd arg isn't the flattened component name of an existing activity:
5118 * dump all activity whose component contains the cmd as a substring
5119 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005120 * <p>
5121 * The caller should not hold lock when calling this method because it will wait for the
5122 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005123 *
5124 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5125 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5126 */
5127 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5128 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5129 ArrayList<ActivityRecord> activities;
5130
5131 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005132 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005133 dumpFocusedStackOnly);
5134 }
5135
5136 if (activities.size() <= 0) {
5137 return false;
5138 }
5139
5140 String[] newArgs = new String[args.length - opti];
5141 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5142
Louis Changcdec0802019-11-11 11:45:07 +08005143 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005144 boolean needSep = false;
5145 for (int i = activities.size() - 1; i >= 0; i--) {
5146 ActivityRecord r = activities.get(i);
5147 if (needSep) {
5148 pw.println();
5149 }
5150 needSep = true;
5151 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005152 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005153 if (lastTask != task) {
5154 lastTask = task;
5155 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005156 pw.print(" id="); pw.print(lastTask.mTaskId);
5157 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005158 if (dumpAll) {
5159 lastTask.dump(pw, " ");
5160 }
5161 }
5162 }
5163 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5164 }
5165 return true;
5166 }
5167
5168 /**
5169 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5170 * there is a thread associated with the activity.
5171 */
5172 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5173 final ActivityRecord r, String[] args, boolean dumpAll) {
5174 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005175 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005176 synchronized (mGlobalLock) {
5177 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5178 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5179 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005180 if (r.hasProcess()) {
5181 pw.println(r.app.getPid());
5182 appThread = r.app.getThread();
5183 } else {
5184 pw.println("(not running)");
5185 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005186 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005187 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005188 }
5189 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005190 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005191 // flush anything that is already in the PrintWriter since the thread is going
5192 // to write to the file descriptor directly
5193 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005194 try (TransferPipe tp = new TransferPipe()) {
5195 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5196 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005197 } catch (IOException e) {
5198 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5199 } catch (RemoteException e) {
5200 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5201 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005202 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005203 }
5204
sanryhuang498e77e2018-12-06 14:57:01 +08005205 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5206 boolean testPssMode) {
5207 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5208 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5209 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005210 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005211 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5212 st.toString());
5213 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005214 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5215 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5216 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005217 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5218 testPssMode);
5219 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005220 }
5221
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222 int getCurrentUserId() {
5223 return mAmInternal.getCurrentUserId();
5224 }
5225
5226 private void enforceNotIsolatedCaller(String caller) {
5227 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5228 throw new SecurityException("Isolated process not allowed to call " + caller);
5229 }
5230 }
5231
Wale Ogunwalef6733932018-06-27 05:14:34 -07005232 public Configuration getConfiguration() {
5233 Configuration ci;
5234 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005235 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005236 ci.userSetLocale = false;
5237 }
5238 return ci;
5239 }
5240
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241 /**
5242 * Current global configuration information. Contains general settings for the entire system,
5243 * also corresponds to the merged configuration of the default display.
5244 */
5245 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005246 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005247 // while initializing process record for system, see {@link
5248 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005249 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005250 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 }
5252
5253 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5254 boolean initLocale) {
5255 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5256 }
5257
5258 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5259 boolean initLocale, boolean deferResume) {
5260 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5261 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5262 UserHandle.USER_NULL, deferResume);
5263 }
5264
Wale Ogunwale59507092018-10-29 09:00:30 -07005265 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266 final long origId = Binder.clearCallingIdentity();
5267 try {
5268 synchronized (mGlobalLock) {
5269 updateConfigurationLocked(values, null, false, true, userId,
5270 false /* deferResume */);
5271 }
5272 } finally {
5273 Binder.restoreCallingIdentity(origId);
5274 }
5275 }
5276
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005277 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5278 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5279 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5280 deferResume, null /* result */);
5281 }
5282
5283 /**
5284 * Do either or both things: (1) change the current configuration, and (2)
5285 * make sure the given activity is running with the (now) current
5286 * configuration. Returns true if the activity has been left running, or
5287 * false if <var>starting</var> is being destroyed to match the new
5288 * configuration.
5289 *
5290 * @param userId is only used when persistent parameter is set to true to persist configuration
5291 * for that particular user
5292 */
5293 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5294 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5295 ActivityTaskManagerService.UpdateConfigurationResult result) {
5296 int changes = 0;
5297 boolean kept = true;
5298
Riddle Hsua0022cd2019-09-09 21:12:41 +08005299 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300 try {
5301 if (values != null) {
5302 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5303 deferResume);
5304 }
5305
5306 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5307 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005308 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309 }
5310
5311 if (result != null) {
5312 result.changes = changes;
5313 result.activityRelaunched = !kept;
5314 }
5315 return kept;
5316 }
5317
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005318 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005319 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005320 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005321
Louis Chang677921f2019-12-06 16:44:24 +08005322 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005323 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005324
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005325 mTempConfig.setTo(getGlobalConfiguration());
5326 final int changes = mTempConfig.updateFrom(values);
5327 if (changes == 0) {
5328 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5329 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5330 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5331 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005332 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005333 return 0;
5334 }
5335
5336 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5337 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005338 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005339 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5340 values.colorMode,
5341 values.densityDpi,
5342 values.fontScale,
5343 values.hardKeyboardHidden,
5344 values.keyboard,
5345 values.keyboardHidden,
5346 values.mcc,
5347 values.mnc,
5348 values.navigation,
5349 values.navigationHidden,
5350 values.orientation,
5351 values.screenHeightDp,
5352 values.screenLayout,
5353 values.screenWidthDp,
5354 values.smallestScreenWidthDp,
5355 values.touchscreen,
5356 values.uiMode);
5357
5358
5359 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5360 final LocaleList locales = values.getLocales();
5361 int bestLocaleIndex = 0;
5362 if (locales.size() > 1) {
5363 if (mSupportedSystemLocales == null) {
5364 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5365 }
5366 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5367 }
5368 SystemProperties.set("persist.sys.locale",
5369 locales.get(bestLocaleIndex).toLanguageTag());
5370 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005371
5372 final Message m = PooledLambda.obtainMessage(
5373 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5374 locales.get(bestLocaleIndex));
5375 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005376 }
5377
Yunfan Chen75157d72018-07-27 14:47:21 +09005378 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005379
5380 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005381 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005382
5383 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5384 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005385 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005386
5387 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005388 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005389
5390 AttributeCache ac = AttributeCache.instance();
5391 if (ac != null) {
5392 ac.updateConfiguration(mTempConfig);
5393 }
5394
5395 // Make sure all resources in our process are updated right now, so that anyone who is going
5396 // to retrieve resource values after we return will be sure to get the new ones. This is
5397 // especially important during boot, where the first config change needs to guarantee all
5398 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005399 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005400
5401 // We need another copy of global config because we're scheduling some calls instead of
5402 // running them in place. We need to be sure that object we send will be handled unchanged.
5403 final Configuration configCopy = new Configuration(mTempConfig);
5404 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005405 final Message msg = PooledLambda.obtainMessage(
5406 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5407 this, userId, configCopy);
5408 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005409 }
5410
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005411 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5412 for (int i = pidMap.size() - 1; i >= 0; i--) {
5413 final int pid = pidMap.keyAt(i);
5414 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005415 if (DEBUG_CONFIGURATION) {
5416 Slog.v(TAG_CONFIGURATION, "Update process config of "
5417 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005418 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005419 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005420 }
5421
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005422 final Message msg = PooledLambda.obtainMessage(
5423 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5424 mAmInternal, changes, initLocale);
5425 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005426
5427 // Override configuration of the default display duplicates global config, so we need to
5428 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005429 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005430 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005431
5432 return changes;
5433 }
5434
Riddle Hsua0022cd2019-09-09 21:12:41 +08005435 /** @see WindowSurfacePlacer#deferLayout */
5436 void deferWindowLayout() {
5437 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5438 // Reset the reasons at the first entrance because we only care about the changes in the
5439 // deferred scope.
5440 mLayoutReasons = 0;
5441 }
5442
5443 mWindowManager.mWindowPlacerLocked.deferLayout();
5444 }
5445
5446 /** @see WindowSurfacePlacer#continueLayout */
5447 void continueWindowLayout() {
5448 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5449 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5450 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5451 }
5452 }
5453
5454 /**
5455 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5456 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5457 * defer count is gone.
5458 */
5459 void addWindowLayoutReasons(@LayoutReason int reasons) {
5460 mLayoutReasons |= reasons;
5461 }
5462
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 private void updateEventDispatchingLocked(boolean booted) {
5464 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5465 }
5466
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005467 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5468 final ContentResolver resolver = mContext.getContentResolver();
5469 Settings.System.putConfigurationForUser(resolver, config, userId);
5470 }
5471
5472 private void sendLocaleToMountDaemonMsg(Locale l) {
5473 try {
5474 IBinder service = ServiceManager.getService("mount");
5475 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5476 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5477 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5478 } catch (RemoteException e) {
5479 Log.e(TAG, "Error storing locale for decryption UI", e);
5480 }
5481 }
5482
Alison Cichowlas3e340502018-08-07 17:15:01 -04005483 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5484 mStartActivitySources.remove(permissionToken);
5485 mExpiredStartAsCallerTokens.add(permissionToken);
5486 }
5487
5488 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5489 mExpiredStartAsCallerTokens.remove(permissionToken);
5490 }
5491
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005492 boolean isActivityStartsLoggingEnabled() {
5493 return mAmInternal.isActivityStartsLoggingEnabled();
5494 }
5495
Michal Karpinski8596ded2018-11-14 14:43:48 +00005496 boolean isBackgroundActivityStartsEnabled() {
5497 return mAmInternal.isBackgroundActivityStartsEnabled();
5498 }
5499
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005501 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005502 mWindowManager.enableScreenAfterBoot();
5503
5504 synchronized (mGlobalLock) {
5505 updateEventDispatchingLocked(booted);
5506 }
5507 }
5508
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005509 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5510 if (r == null || !r.hasProcess()) {
5511 return KEY_DISPATCHING_TIMEOUT_MS;
5512 }
5513 return getInputDispatchingTimeoutLocked(r.app);
5514 }
5515
5516 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005517 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005518 }
5519
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 /**
5521 * Decide based on the configuration whether we should show the ANR,
5522 * crash, etc dialogs. The idea is that if there is no affordance to
5523 * press the on-screen buttons, or the user experience would be more
5524 * greatly impacted than the crash itself, we shouldn't show the dialog.
5525 *
5526 * A thought: SystemUI might also want to get told about this, the Power
5527 * dialog / global actions also might want different behaviors.
5528 */
5529 private void updateShouldShowDialogsLocked(Configuration config) {
5530 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5531 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5532 && config.navigation == Configuration.NAVIGATION_NONAV);
5533 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5534 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5535 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5536 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5537 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5538 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5539 HIDE_ERROR_DIALOGS, 0) != 0;
5540 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5541 }
5542
5543 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5544 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5545 FONT_SCALE, 1.0f, userId);
5546
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005547 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 if (getGlobalConfiguration().fontScale == scaleFactor) {
5549 return;
5550 }
5551
5552 final Configuration configuration
5553 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5554 configuration.fontScale = scaleFactor;
5555 updatePersistentConfiguration(configuration, userId);
5556 }
5557 }
5558
5559 // Actually is sleeping or shutting down or whatever else in the future
5560 // is an inactive state.
5561 boolean isSleepingOrShuttingDownLocked() {
5562 return isSleepingLocked() || mShuttingDown;
5563 }
5564
5565 boolean isSleepingLocked() {
5566 return mSleeping;
5567 }
5568
Riddle Hsu16567132018-08-16 21:37:47 +08005569 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005570 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005571 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 if (task.isActivityTypeStandard()) {
5573 if (mCurAppTimeTracker != r.appTimeTracker) {
5574 // We are switching app tracking. Complete the current one.
5575 if (mCurAppTimeTracker != null) {
5576 mCurAppTimeTracker.stop();
5577 mH.obtainMessage(
5578 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005579 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005580 mCurAppTimeTracker = null;
5581 }
5582 if (r.appTimeTracker != null) {
5583 mCurAppTimeTracker = r.appTimeTracker;
5584 startTimeTrackingFocusedActivityLocked();
5585 }
5586 } else {
5587 startTimeTrackingFocusedActivityLocked();
5588 }
5589 } else {
5590 r.appTimeTracker = null;
5591 }
5592 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5593 // TODO: Probably not, because we don't want to resume voice on switching
5594 // back to this activity
5595 if (task.voiceInteractor != null) {
5596 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5597 } else {
5598 finishRunningVoiceLocked();
5599
5600 if (mLastResumedActivity != null) {
5601 final IVoiceInteractionSession session;
5602
Louis Changcdec0802019-11-11 11:45:07 +08005603 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005604 if (lastResumedActivityTask != null
5605 && lastResumedActivityTask.voiceSession != null) {
5606 session = lastResumedActivityTask.voiceSession;
5607 } else {
5608 session = mLastResumedActivity.voiceSession;
5609 }
5610
5611 if (session != null) {
5612 // We had been in a voice interaction session, but now focused has
5613 // move to something different. Just finish the session, we can't
5614 // return to it and retain the proper state and synchronization with
5615 // the voice interaction service.
5616 finishVoiceTask(session);
5617 }
5618 }
5619 }
5620
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005621 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5622 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005623 }
5624 updateResumedAppTrace(r);
5625 mLastResumedActivity = r;
5626
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005627 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005628
5629 applyUpdateLockStateLocked(r);
5630 applyUpdateVrModeLocked(r);
5631
Jeff Changd136e772019-11-05 20:33:52 +08005632 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005633 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005634 r == null ? "NULL" : r.shortComponentName,
5635 reason);
5636 }
5637
5638 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5639 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005640 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005641 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005642 updateSleepIfNeededLocked();
5643 return token;
5644 }
5645 }
5646
5647 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005648 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005649 final boolean wasSleeping = mSleeping;
5650 boolean updateOomAdj = false;
5651
5652 if (!shouldSleep) {
5653 // If wasSleeping is true, we need to wake up activity manager state from when
5654 // we started sleeping. In either case, we need to apply the sleep tokens, which
5655 // will wake up stacks or put them to sleep as appropriate.
5656 if (wasSleeping) {
5657 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005658 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5659 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005660 startTimeTrackingFocusedActivityLocked();
5661 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005662 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005663 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5664 }
Louis Chang149d5c82019-12-30 09:47:39 +08005665 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005666 if (wasSleeping) {
5667 updateOomAdj = true;
5668 }
5669 } else if (!mSleeping && shouldSleep) {
5670 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005671 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5672 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005673 if (mCurAppTimeTracker != null) {
5674 mCurAppTimeTracker.stop();
5675 }
5676 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005677 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005678 mStackSupervisor.goingToSleepLocked();
5679 updateResumedAppTrace(null /* resumed */);
5680 updateOomAdj = true;
5681 }
5682 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005683 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005684 }
5685 }
5686
5687 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005688 mH.removeCallbacks(mUpdateOomAdjRunnable);
5689 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005690 }
5691
Wale Ogunwale53783742018-09-16 10:21:51 -07005692 void updateCpuStats() {
5693 mH.post(mAmInternal::updateCpuStats);
5694 }
5695
Hui Yu03d12402018-12-06 18:00:37 -08005696 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5697 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005698 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5699 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005700 mH.sendMessage(m);
5701 }
5702
Hui Yu03d12402018-12-06 18:00:37 -08005703 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005704 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005705 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005706 if (task != null) {
5707 final ActivityRecord rootActivity = task.getRootActivity();
5708 if (rootActivity != null) {
5709 taskRoot = rootActivity.mActivityComponent;
5710 }
5711 }
5712
Hui Yu03d12402018-12-06 18:00:37 -08005713 final Message m = PooledLambda.obtainMessage(
5714 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005715 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005716 mH.sendMessage(m);
5717 }
5718
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005719 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5720 String hostingType) {
5721 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005722 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5723 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005724 + activity.processName);
5725 }
5726 // Post message to start process to avoid possible deadlock of calling into AMS with the
5727 // ATMS lock held.
5728 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5729 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5730 isTop, hostingType, activity.intent.getComponent());
5731 mH.sendMessage(m);
5732 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005733 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005734 }
5735 }
5736
Wale Ogunwale53783742018-09-16 10:21:51 -07005737 void setBooting(boolean booting) {
5738 mAmInternal.setBooting(booting);
5739 }
5740
5741 boolean isBooting() {
5742 return mAmInternal.isBooting();
5743 }
5744
5745 void setBooted(boolean booted) {
5746 mAmInternal.setBooted(booted);
5747 }
5748
5749 boolean isBooted() {
5750 return mAmInternal.isBooted();
5751 }
5752
5753 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5754 mH.post(() -> {
5755 if (finishBooting) {
5756 mAmInternal.finishBooting();
5757 }
5758 if (enableScreen) {
5759 mInternal.enableScreenAfterBoot(isBooted());
5760 }
5761 });
5762 }
5763
5764 void setHeavyWeightProcess(ActivityRecord root) {
5765 mHeavyWeightProcess = root.app;
5766 final Message m = PooledLambda.obtainMessage(
5767 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005768 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005769 mH.sendMessage(m);
5770 }
5771
5772 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5773 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5774 return;
5775 }
5776
5777 mHeavyWeightProcess = null;
5778 final Message m = PooledLambda.obtainMessage(
5779 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5780 proc.mUserId);
5781 mH.sendMessage(m);
5782 }
5783
5784 private void cancelHeavyWeightProcessNotification(int userId) {
5785 final INotificationManager inm = NotificationManager.getService();
5786 if (inm == null) {
5787 return;
5788 }
5789 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005790 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005791 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5792 } catch (RuntimeException e) {
5793 Slog.w(TAG, "Error canceling notification for service", e);
5794 } catch (RemoteException e) {
5795 }
5796
5797 }
5798
5799 private void postHeavyWeightProcessNotification(
5800 WindowProcessController proc, Intent intent, int userId) {
5801 if (proc == null) {
5802 return;
5803 }
5804
5805 final INotificationManager inm = NotificationManager.getService();
5806 if (inm == null) {
5807 return;
5808 }
5809
5810 try {
5811 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5812 String text = mContext.getString(R.string.heavy_weight_notification,
5813 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5814 Notification notification =
5815 new Notification.Builder(context,
5816 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5817 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5818 .setWhen(0)
5819 .setOngoing(true)
5820 .setTicker(text)
5821 .setColor(mContext.getColor(
5822 com.android.internal.R.color.system_notification_accent_color))
5823 .setContentTitle(text)
5824 .setContentText(
5825 mContext.getText(R.string.heavy_weight_notification_detail))
5826 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5827 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5828 new UserHandle(userId)))
5829 .build();
5830 try {
5831 inm.enqueueNotificationWithTag("android", "android", null,
5832 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5833 } catch (RuntimeException e) {
5834 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5835 } catch (RemoteException e) {
5836 }
5837 } catch (PackageManager.NameNotFoundException e) {
5838 Slog.w(TAG, "Unable to create context for heavy notification", e);
5839 }
5840
5841 }
5842
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005843 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5844 IBinder token, String resultWho, int requestCode, Intent[] intents,
5845 String[] resolvedTypes, int flags, Bundle bOptions) {
5846
5847 ActivityRecord activity = null;
5848 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5849 activity = ActivityRecord.isInStackLocked(token);
5850 if (activity == null) {
5851 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5852 return null;
5853 }
5854 if (activity.finishing) {
5855 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5856 return null;
5857 }
5858 }
5859
5860 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5861 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5862 bOptions);
5863 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5864 if (noCreate) {
5865 return rec;
5866 }
5867 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5868 if (activity.pendingResults == null) {
5869 activity.pendingResults = new HashSet<>();
5870 }
5871 activity.pendingResults.add(rec.ref);
5872 }
5873 return rec;
5874 }
5875
Andrii Kulian52d255c2018-07-13 11:32:19 -07005876 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005877 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005878 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005879 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5880 mCurAppTimeTracker.start(resumedActivity.packageName);
5881 }
5882 }
5883
5884 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5885 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005886 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005887 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5888 }
5889 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005890 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005891 constructResumedTraceName(resumed.packageName), 0);
5892 }
5893 mTracedResumedActivity = resumed;
5894 }
5895
5896 private String constructResumedTraceName(String packageName) {
5897 return "focused app: " + packageName;
5898 }
5899
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005900 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005901 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005902 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005903 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005904 // mainStack is null during startup.
5905 if (mainStack != null) {
5906 if (changes != 0 && starting == null) {
5907 // If the configuration changed, and the caller is not already
5908 // in the process of starting an activity, then find the top
5909 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005910 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005911 }
5912
5913 if (starting != null) {
5914 kept = starting.ensureActivityConfiguration(changes,
5915 false /* preserveWindow */);
5916 // And we need to make sure at this point that all other activities
5917 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005918 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005919 !PRESERVE_WINDOWS);
5920 }
5921 }
5922
5923 return kept;
5924 }
5925
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005926 void scheduleAppGcsLocked() {
5927 mH.post(() -> mAmInternal.scheduleAppGcs());
5928 }
5929
Wale Ogunwale53783742018-09-16 10:21:51 -07005930 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5931 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5932 }
5933
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005934 /**
5935 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5936 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5937 * on demand.
5938 */
5939 IPackageManager getPackageManager() {
5940 return AppGlobals.getPackageManager();
5941 }
5942
5943 PackageManagerInternal getPackageManagerInternalLocked() {
5944 if (mPmInternal == null) {
5945 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5946 }
5947 return mPmInternal;
5948 }
5949
Hai Zhangf4da9be2019-05-01 13:46:06 +08005950 PermissionPolicyInternal getPermissionPolicyInternal() {
5951 if (mPermissionPolicyInternal == null) {
5952 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5953 }
5954 return mPermissionPolicyInternal;
5955 }
5956
Wale Ogunwale008163e2018-07-23 23:11:08 -07005957 AppWarnings getAppWarningsLocked() {
5958 return mAppWarnings;
5959 }
5960
Wale Ogunwale214f3482018-10-04 11:00:47 -07005961 Intent getHomeIntent() {
5962 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5963 intent.setComponent(mTopComponent);
5964 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5965 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5966 intent.addCategory(Intent.CATEGORY_HOME);
5967 }
5968 return intent;
5969 }
5970
Chilun2ef71f72018-11-16 17:57:15 +08005971 /**
5972 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5973 * activities.
5974 *
5975 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5976 * component defined in config_secondaryHomeComponent.
5977 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5978 */
5979 Intent getSecondaryHomeIntent(String preferredPackage) {
5980 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005981 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5982 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5983 if (preferredPackage == null || useSystemProvidedLauncher) {
5984 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005985 final String secondaryHomeComponent = mContext.getResources().getString(
5986 com.android.internal.R.string.config_secondaryHomeComponent);
5987 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5988 } else {
5989 intent.setPackage(preferredPackage);
5990 }
5991 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5992 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5993 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5994 }
5995 return intent;
5996 }
5997
Wale Ogunwale214f3482018-10-04 11:00:47 -07005998 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5999 if (info == null) return null;
6000 ApplicationInfo newInfo = new ApplicationInfo(info);
6001 newInfo.initForUser(userId);
6002 return newInfo;
6003 }
6004
Wale Ogunwale9c103022018-10-18 07:44:54 -07006005 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006006 if (uid == SYSTEM_UID) {
6007 // The system gets to run in any process. If there are multiple processes with the same
6008 // uid, just pick the first (this should never happen).
6009 final SparseArray<WindowProcessController> procs =
6010 mProcessNames.getMap().get(processName);
6011 if (procs == null) return null;
6012 final int procCount = procs.size();
6013 for (int i = 0; i < procCount; i++) {
6014 final int procUid = procs.keyAt(i);
6015 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
6016 // Don't use an app process or different user process for system component.
6017 continue;
6018 }
6019 return procs.valueAt(i);
6020 }
6021 }
6022
6023 return mProcessNames.get(processName, uid);
6024 }
6025
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006026 WindowProcessController getProcessController(IApplicationThread thread) {
6027 if (thread == null) {
6028 return null;
6029 }
6030
6031 final IBinder threadBinder = thread.asBinder();
6032 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6033 for (int i = pmap.size()-1; i >= 0; i--) {
6034 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6035 for (int j = procs.size() - 1; j >= 0; j--) {
6036 final WindowProcessController proc = procs.valueAt(j);
6037 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6038 return proc;
6039 }
6040 }
6041 }
6042
6043 return null;
6044 }
6045
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006046 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006047 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006048 if (proc == null) return null;
6049 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6050 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006051 }
6052 return null;
6053 }
6054
Riddle Hsua0536432019-02-16 00:38:59 +08006055 int getUidState(int uid) {
6056 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006057 }
6058
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006059 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006060 // A uid is considered to be foreground if it has a visible non-toast window.
6061 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006062 }
6063
Ricky Wai96f5c352019-04-10 18:40:17 +01006064 boolean isDeviceOwner(int uid) {
6065 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006066 }
6067
Ricky Wai96f5c352019-04-10 18:40:17 +01006068 void setDeviceOwnerUid(int uid) {
6069 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006070 }
6071
Wale Ogunwale9de19442018-10-18 19:05:03 -07006072 /**
6073 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6074 * the whitelist
6075 */
6076 String getPendingTempWhitelistTagForUidLocked(int uid) {
6077 return mPendingTempWhitelist.get(uid);
6078 }
6079
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006080 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6081 if (true || Build.IS_USER) {
6082 return;
6083 }
6084
6085 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6086 StrictMode.allowThreadDiskWrites();
6087 try {
6088 File tracesDir = new File("/data/anr");
6089 File tracesFile = null;
6090 try {
6091 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6092
6093 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006094 String timeString =
6095 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6096 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006097 sb.append(": ");
6098 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6099 sb.append(" since ");
6100 sb.append(msg);
6101 FileOutputStream fos = new FileOutputStream(tracesFile);
6102 fos.write(sb.toString().getBytes());
6103 if (app == null) {
6104 fos.write("\n*** No application process!".getBytes());
6105 }
6106 fos.close();
6107 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6108 } catch (IOException e) {
6109 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6110 return;
6111 }
6112
6113 if (app != null && app.getPid() > 0) {
6114 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6115 firstPids.add(app.getPid());
6116 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6117 }
6118
6119 File lastTracesFile = null;
6120 File curTracesFile = null;
6121 for (int i=9; i>=0; i--) {
6122 String name = String.format(Locale.US, "slow%02d.txt", i);
6123 curTracesFile = new File(tracesDir, name);
6124 if (curTracesFile.exists()) {
6125 if (lastTracesFile != null) {
6126 curTracesFile.renameTo(lastTracesFile);
6127 } else {
6128 curTracesFile.delete();
6129 }
6130 }
6131 lastTracesFile = curTracesFile;
6132 }
6133 tracesFile.renameTo(curTracesFile);
6134 } finally {
6135 StrictMode.setThreadPolicy(oldPolicy);
6136 }
6137 }
6138
Michal Karpinskida34cd42019-04-02 19:46:52 +01006139 boolean isAssociatedCompanionApp(int userId, int uid) {
6140 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6141 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006142 return false;
6143 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006144 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006145 }
6146
Issei Suzuki734bc942019-06-05 13:59:52 +02006147 void notifySingleTaskDisplayEmpty(int displayId) {
6148 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6149 }
6150
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006151 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006152 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006153
6154
Wale Ogunwale98875612018-10-12 07:53:02 -07006155 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6156 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006157
Riddle Hsud93a6c42018-11-29 21:50:06 +08006158 H(Looper looper) {
6159 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006160 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006161
6162 @Override
6163 public void handleMessage(Message msg) {
6164 switch (msg.what) {
6165 case REPORT_TIME_TRACKER_MSG: {
6166 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6167 tracker.deliverResult(mContext);
6168 } break;
6169 }
6170 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006171 }
6172
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006173 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006174 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006175
6176 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006177 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006178 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006179
6180 @Override
6181 public void handleMessage(Message msg) {
6182 switch (msg.what) {
6183 case DISMISS_DIALOG_UI_MSG: {
6184 final Dialog d = (Dialog) msg.obj;
6185 d.dismiss();
6186 break;
6187 }
6188 }
6189 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006190 }
6191
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 final class LocalService extends ActivityTaskManagerInternal {
6193 @Override
6194 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006195 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006196 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006197 }
6198
6199 @Override
6200 public ComponentName getHomeActivityForUser(int userId) {
6201 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006202 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006203 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006204 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 }
6206 }
6207
6208 @Override
6209 public void onLocalVoiceInteractionStarted(IBinder activity,
6210 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6211 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006212 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006213 }
6214 }
6215
6216 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006217 public void notifySingleTaskDisplayDrawn(int displayId) {
6218 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6219 }
6220
6221 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 public void notifyAppTransitionFinished() {
6223 synchronized (mGlobalLock) {
6224 mStackSupervisor.notifyAppTransitionDone();
6225 }
6226 }
6227
6228 @Override
6229 public void notifyAppTransitionCancelled() {
6230 synchronized (mGlobalLock) {
6231 mStackSupervisor.notifyAppTransitionDone();
6232 }
6233 }
6234
6235 @Override
6236 public List<IBinder> getTopVisibleActivities() {
6237 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006238 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006239 }
6240 }
6241
6242 @Override
6243 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6244 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006245 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006246 }
6247 }
6248
6249 @Override
6250 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6251 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006252 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 final String[] resolvedTypes = new String[intents.length];
6254
6255 // UID of the package on user userId.
6256 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6257 // packageUid may not be initialized.
6258 int packageUid = 0;
6259 final long ident = Binder.clearCallingIdentity();
6260
6261 try {
6262 for (int i = 0; i < intents.length; i++) {
6263 resolvedTypes[i] =
6264 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6265 }
6266
6267 packageUid = AppGlobals.getPackageManager().getPackageUid(
6268 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6269 } catch (RemoteException e) {
6270 // Shouldn't happen.
6271 } finally {
6272 Binder.restoreCallingIdentity(ident);
6273 }
6274
Riddle Hsu591bf612019-02-14 17:55:31 +08006275 return getActivityStartController().startActivitiesInPackage(
6276 packageUid, packageName,
6277 intents, resolvedTypes, null /* resultTo */,
6278 SafeActivityOptions.fromBundle(bOptions), userId,
6279 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6280 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 }
6282
6283 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006284 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6285 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6286 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6287 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006288 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006289 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006290 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6291 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6292 userId, validateIncomingUser, originatingPendingIntent,
6293 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006294 }
6295 }
6296
6297 @Override
6298 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6299 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6300 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006301 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006302 PendingIntentRecord originatingPendingIntent,
6303 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006304 synchronized (mGlobalLock) {
6305 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6306 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6307 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006308 validateIncomingUser, originatingPendingIntent,
6309 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006310 }
6311 }
6312
6313 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006314 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6315 Intent intent, Bundle options, int userId) {
6316 return ActivityTaskManagerService.this.startActivityAsUser(
6317 caller, callerPacakge, intent,
6318 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6319 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6320 false /*validateIncomingUser*/);
6321 }
6322
6323 @Override
lumark588a3e82018-07-20 18:53:54 +08006324 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 synchronized (mGlobalLock) {
6326
6327 // We might change the visibilities here, so prepare an empty app transition which
6328 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006329 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006330 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006331 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006332 return;
6333 }
Louis Chang677921f2019-12-06 16:44:24 +08006334 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006335 final boolean wasTransitionSet =
6336 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006337 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006338 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006339 }
Louis Chang149d5c82019-12-30 09:47:39 +08006340 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006341
6342 // If there was a transition set already we don't want to interfere with it as we
6343 // might be starting it too early.
6344 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006345 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006346 }
6347 }
6348 if (callback != null) {
6349 callback.run();
6350 }
6351 }
6352
6353 @Override
6354 public void notifyKeyguardTrustedChanged() {
6355 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006356 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006357 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006358 }
6359 }
6360 }
6361
6362 /**
6363 * Called after virtual display Id is updated by
6364 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6365 * {@param vrVr2dDisplayId}.
6366 */
6367 @Override
6368 public void setVr2dDisplayId(int vr2dDisplayId) {
6369 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6370 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006371 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006372 }
6373 }
6374
6375 @Override
6376 public void setFocusedActivity(IBinder token) {
6377 synchronized (mGlobalLock) {
6378 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6379 if (r == null) {
6380 throw new IllegalArgumentException(
6381 "setFocusedActivity: No activity record matching token=" + token);
6382 }
Louis Chang19443452018-10-09 12:10:21 +08006383 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006384 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006385 }
6386 }
6387 }
6388
6389 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006390 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006391 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006392 }
6393
6394 @Override
6395 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006396 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006397 }
6398
6399 @Override
6400 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006401 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006402 }
6403
6404 @Override
6405 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6406 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6407 }
6408
6409 @Override
6410 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006411 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006412 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006413
6414 @Override
6415 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6416 synchronized (mGlobalLock) {
6417 mActiveVoiceInteractionServiceComponent = component;
6418 }
6419 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006420
6421 @Override
6422 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6423 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6424 return;
6425 }
6426 synchronized (mGlobalLock) {
6427 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6428 if (types == null) {
6429 if (uid < 0) {
6430 return;
6431 }
6432 types = new ArrayMap<>();
6433 mAllowAppSwitchUids.put(userId, types);
6434 }
6435 if (uid < 0) {
6436 types.remove(type);
6437 } else {
6438 types.put(type, uid);
6439 }
6440 }
6441 }
6442
6443 @Override
6444 public void onUserStopped(int userId) {
6445 synchronized (mGlobalLock) {
6446 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6447 mAllowAppSwitchUids.remove(userId);
6448 }
6449 }
6450
6451 @Override
6452 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6453 synchronized (mGlobalLock) {
6454 return ActivityTaskManagerService.this.isGetTasksAllowed(
6455 caller, callingPid, callingUid);
6456 }
6457 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006458
Riddle Hsua0536432019-02-16 00:38:59 +08006459 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006460 @Override
6461 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006462 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006463 mProcessNames.put(proc.mName, proc.mUid, proc);
6464 }
6465 }
6466
Riddle Hsua0536432019-02-16 00:38:59 +08006467 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006468 @Override
6469 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006470 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006471 mProcessNames.remove(name, uid);
6472 }
6473 }
6474
Riddle Hsua0536432019-02-16 00:38:59 +08006475 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006476 @Override
6477 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006478 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006479 if (proc == mHomeProcess) {
6480 mHomeProcess = null;
6481 }
6482 if (proc == mPreviousProcess) {
6483 mPreviousProcess = null;
6484 }
6485 }
6486 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006487
Riddle Hsua0536432019-02-16 00:38:59 +08006488 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006489 @Override
6490 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006491 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006492 return mTopProcessState;
6493 }
6494 }
6495
Riddle Hsua0536432019-02-16 00:38:59 +08006496 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006497 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006498 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006499 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006500 return proc == mHeavyWeightProcess;
6501 }
6502 }
6503
Riddle Hsua0536432019-02-16 00:38:59 +08006504 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006505 @Override
6506 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006507 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006508 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6509 }
6510 }
6511
6512 @Override
6513 public void finishHeavyWeightApp() {
6514 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006515 if (mHeavyWeightProcess != null) {
6516 mHeavyWeightProcess.finishActivities();
6517 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006518 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6519 mHeavyWeightProcess);
6520 }
6521 }
6522
Riddle Hsua0536432019-02-16 00:38:59 +08006523 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006524 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006525 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006526 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006527 return isSleepingLocked();
6528 }
6529 }
6530
6531 @Override
6532 public boolean isShuttingDown() {
6533 synchronized (mGlobalLock) {
6534 return mShuttingDown;
6535 }
6536 }
6537
6538 @Override
6539 public boolean shuttingDown(boolean booted, int timeout) {
6540 synchronized (mGlobalLock) {
6541 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006542 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006543 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006544 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006545 return mStackSupervisor.shutdownLocked(timeout);
6546 }
6547 }
6548
6549 @Override
6550 public void enableScreenAfterBoot(boolean booted) {
6551 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006552 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006553 mWindowManager.enableScreenAfterBoot();
6554 updateEventDispatchingLocked(booted);
6555 }
6556 }
6557
6558 @Override
6559 public boolean showStrictModeViolationDialog() {
6560 synchronized (mGlobalLock) {
6561 return mShowDialogs && !mSleeping && !mShuttingDown;
6562 }
6563 }
6564
6565 @Override
6566 public void showSystemReadyErrorDialogsIfNeeded() {
6567 synchronized (mGlobalLock) {
6568 try {
6569 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6570 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6571 + " data partition or your device will be unstable.");
6572 mUiHandler.post(() -> {
6573 if (mShowDialogs) {
6574 AlertDialog d = new BaseErrorDialog(mUiContext);
6575 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6576 d.setCancelable(false);
6577 d.setTitle(mUiContext.getText(R.string.android_system_label));
6578 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6579 d.setButton(DialogInterface.BUTTON_POSITIVE,
6580 mUiContext.getText(R.string.ok),
6581 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6582 d.show();
6583 }
6584 });
6585 }
6586 } catch (RemoteException e) {
6587 }
6588
6589 if (!Build.isBuildConsistent()) {
6590 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6591 mUiHandler.post(() -> {
6592 if (mShowDialogs) {
6593 AlertDialog d = new BaseErrorDialog(mUiContext);
6594 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6595 d.setCancelable(false);
6596 d.setTitle(mUiContext.getText(R.string.android_system_label));
6597 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6598 d.setButton(DialogInterface.BUTTON_POSITIVE,
6599 mUiContext.getText(R.string.ok),
6600 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6601 d.show();
6602 }
6603 });
6604 }
6605 }
6606 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006607
6608 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006609 public void onProcessMapped(int pid, WindowProcessController proc) {
6610 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006611 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006612 }
6613 }
6614
6615 @Override
6616 public void onProcessUnMapped(int pid) {
6617 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006618 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006619 }
6620 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006621
6622 @Override
6623 public void onPackageDataCleared(String name) {
6624 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006625 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006626 mAppWarnings.onPackageDataCleared(name);
6627 }
6628 }
6629
6630 @Override
6631 public void onPackageUninstalled(String name) {
6632 synchronized (mGlobalLock) {
6633 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006634 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006635 }
6636 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006637
6638 @Override
6639 public void onPackageAdded(String name, boolean replacing) {
6640 synchronized (mGlobalLock) {
6641 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6642 }
6643 }
6644
6645 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006646 public void onPackageReplaced(ApplicationInfo aInfo) {
6647 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006648 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006649 }
6650 }
6651
6652 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006653 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6654 synchronized (mGlobalLock) {
6655 return compatibilityInfoForPackageLocked(ai);
6656 }
6657 }
6658
Yunfan Chen75157d72018-07-27 14:47:21 +09006659 /**
6660 * Set the corresponding display information for the process global configuration. To be
6661 * called when we need to show IME on a different display.
6662 *
6663 * @param pid The process id associated with the IME window.
6664 * @param displayId The ID of the display showing the IME.
6665 */
6666 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006667 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006668 // Don't update process-level configuration for Multi-Client IME process since other
6669 // IMEs on other displays will also receive this configuration change due to IME
6670 // services use the same application config/context.
6671 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006672
Yunfan Chen75157d72018-07-27 14:47:21 +09006673 if (pid == MY_PID || pid < 0) {
6674 if (DEBUG_CONFIGURATION) {
6675 Slog.w(TAG,
6676 "Trying to update display configuration for system/invalid process.");
6677 }
6678 return;
6679 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006680 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006681 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006682 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006683 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006684 // Call might come when display is not yet added or has been removed.
6685 if (DEBUG_CONFIGURATION) {
6686 Slog.w(TAG, "Trying to update display configuration for non-existing "
6687 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006688 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006689 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006690 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006691 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006692 if (process == null) {
6693 if (DEBUG_CONFIGURATION) {
6694 Slog.w(TAG, "Trying to update display configuration for invalid "
6695 + "process, pid=" + pid);
6696 }
6697 return;
6698 }
lumarkddc77fb2019-06-27 22:22:23 +08006699 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006700 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006701 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006702 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006703
6704 @Override
6705 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006706 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006707 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006708 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6709 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006710 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006711 }
6712 }
6713 }
6714
6715 @Override
6716 public void clearPendingResultForActivity(IBinder activityToken,
6717 WeakReference<PendingIntentRecord> pir) {
6718 synchronized (mGlobalLock) {
6719 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6720 if (r != null && r.pendingResults != null) {
6721 r.pendingResults.remove(pir);
6722 }
6723 }
6724 }
6725
6726 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006727 public ActivityTokens getTopActivityForTask(int taskId) {
6728 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006729 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006730 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006731 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6732 + " Requested task not found");
6733 return null;
6734 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006735 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006736 if (activity == null) {
6737 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6738 + " Requested activity not found");
6739 return null;
6740 }
6741 if (!activity.attachedToProcess()) {
6742 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6743 + activity);
6744 return null;
6745 }
6746 return new ActivityTokens(activity.appToken, activity.assistToken,
6747 activity.app.getThread());
6748 }
6749 }
6750
6751 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006752 public IIntentSender getIntentSender(int type, String packageName,
6753 int callingUid, int userId, IBinder token, String resultWho,
6754 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6755 Bundle bOptions) {
6756 synchronized (mGlobalLock) {
6757 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6758 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6759 }
6760 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006761
6762 @Override
6763 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6764 synchronized (mGlobalLock) {
6765 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6766 if (r == null) {
6767 return null;
6768 }
6769 if (r.mServiceConnectionsHolder == null) {
6770 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6771 ActivityTaskManagerService.this, r);
6772 }
6773
6774 return r.mServiceConnectionsHolder;
6775 }
6776 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006777
6778 @Override
6779 public Intent getHomeIntent() {
6780 synchronized (mGlobalLock) {
6781 return ActivityTaskManagerService.this.getHomeIntent();
6782 }
6783 }
6784
6785 @Override
6786 public boolean startHomeActivity(int userId, String reason) {
6787 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006788 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006789 }
6790 }
6791
6792 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006793 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006794 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006795 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006796 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006797 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006798 }
Chilun8b1f1be2019-03-13 17:14:36 +08006799 }
6800
6801 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006802 public boolean startHomeOnAllDisplays(int userId, String reason) {
6803 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006804 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006805 }
6806 }
6807
Riddle Hsua0536432019-02-16 00:38:59 +08006808 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006809 @Override
6810 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006811 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006812 if (mFactoryTest == FACTORY_TEST_OFF) {
6813 return false;
6814 }
6815 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6816 && wpc.mName.equals(mTopComponent.getPackageName())) {
6817 return true;
6818 }
6819 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6820 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6821 }
6822 }
6823
6824 @Override
6825 public void updateTopComponentForFactoryTest() {
6826 synchronized (mGlobalLock) {
6827 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6828 return;
6829 }
6830 final ResolveInfo ri = mContext.getPackageManager()
6831 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6832 final CharSequence errorMsg;
6833 if (ri != null) {
6834 final ActivityInfo ai = ri.activityInfo;
6835 final ApplicationInfo app = ai.applicationInfo;
6836 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6837 mTopAction = Intent.ACTION_FACTORY_TEST;
6838 mTopData = null;
6839 mTopComponent = new ComponentName(app.packageName, ai.name);
6840 errorMsg = null;
6841 } else {
6842 errorMsg = mContext.getResources().getText(
6843 com.android.internal.R.string.factorytest_not_system);
6844 }
6845 } else {
6846 errorMsg = mContext.getResources().getText(
6847 com.android.internal.R.string.factorytest_no_action);
6848 }
6849 if (errorMsg == null) {
6850 return;
6851 }
6852
6853 mTopAction = null;
6854 mTopData = null;
6855 mTopComponent = null;
6856 mUiHandler.post(() -> {
6857 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6858 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006859 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006860 });
6861 }
6862 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006863
Riddle Hsua0536432019-02-16 00:38:59 +08006864 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 @Override
6866 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6867 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006868 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006869 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006870 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006871
6872 wpc.clearRecentTasks();
6873 wpc.clearActivities();
6874
6875 if (wpc.isInstrumenting()) {
6876 finishInstrumentationCallback.run();
6877 }
6878
Jorim Jaggid0752812018-10-16 16:07:20 +02006879 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006880 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006881 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006882 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006883 // If there was nothing to resume, and we are not already restarting
6884 // this process, but there is a visible activity that is hosted by the
6885 // process...then make sure all visible activities are running, taking
6886 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006887 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006888 !PRESERVE_WINDOWS);
6889 }
6890 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006891 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006893 }
6894 }
6895 }
6896
6897 @Override
6898 public void closeSystemDialogs(String reason) {
6899 enforceNotIsolatedCaller("closeSystemDialogs");
6900
6901 final int pid = Binder.getCallingPid();
6902 final int uid = Binder.getCallingUid();
6903 final long origId = Binder.clearCallingIdentity();
6904 try {
6905 synchronized (mGlobalLock) {
6906 // Only allow this from foreground processes, so that background
6907 // applications can't abuse it to prevent system UI from being shown.
6908 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006909 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006910 if (!proc.isPerceptible()) {
6911 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6912 + " from background process " + proc);
6913 return;
6914 }
6915 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006916 mWindowManager.closeSystemDialogs(reason);
6917
Louis Chang149d5c82019-12-30 09:47:39 +08006918 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006920 // Call into AM outside the synchronized block.
6921 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 } finally {
6923 Binder.restoreCallingIdentity(origId);
6924 }
6925 }
6926
6927 @Override
6928 public void cleanupDisabledPackageComponents(
6929 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6930 synchronized (mGlobalLock) {
6931 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006932 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006933 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006934 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006935 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 }
6937
6938 // Clean-up disabled tasks
6939 getRecentTasks().cleanupDisabledPackageTasksLocked(
6940 packageName, disabledClasses, userId);
6941 }
6942 }
6943
6944 @Override
6945 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6946 int userId) {
6947 synchronized (mGlobalLock) {
6948
6949 boolean didSomething =
6950 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006951 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006952 null, doit, evenPersistent, userId);
6953 return didSomething;
6954 }
6955 }
6956
6957 @Override
6958 public void resumeTopActivities(boolean scheduleIdle) {
6959 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006960 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006961 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006962 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 }
6964 }
6965 }
6966
Riddle Hsua0536432019-02-16 00:38:59 +08006967 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006968 @Override
6969 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006970 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006971 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6972 }
6973 }
6974
Riddle Hsua0536432019-02-16 00:38:59 +08006975 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006976 @Override
6977 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006978 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006979 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6980 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6981 }
6982 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006983 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006984 } finally {
6985 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6986 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006987 }
6988 }
6989
6990 @Override
6991 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6992 try {
6993 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6994 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6995 }
6996 } catch (RemoteException ex) {
6997 throw new SecurityException("Fail to check is caller a privileged app", ex);
6998 }
6999
7000 synchronized (mGlobalLock) {
7001 final long ident = Binder.clearCallingIdentity();
7002 try {
7003 if (mAmInternal.shouldConfirmCredentials(userId)) {
7004 if (mKeyguardController.isKeyguardLocked()) {
7005 // Showing launcher to avoid user entering credential twice.
7006 startHomeActivity(currentUserId, "notifyLockedProfile");
7007 }
Louis Chang149d5c82019-12-30 09:47:39 +08007008 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007009 }
7010 } finally {
7011 Binder.restoreCallingIdentity(ident);
7012 }
7013 }
7014 }
7015
7016 @Override
7017 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7018 mAmInternal.enforceCallingPermission(
7019 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7020
7021 synchronized (mGlobalLock) {
7022 final long ident = Binder.clearCallingIdentity();
7023 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007024 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7025 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007026 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007027 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7028 UserHandle.CURRENT);
7029 } finally {
7030 Binder.restoreCallingIdentity(ident);
7031 }
7032 }
7033 }
7034
7035 @Override
7036 public void writeActivitiesToProto(ProtoOutputStream proto) {
7037 synchronized (mGlobalLock) {
7038 // The output proto of "activity --proto activities"
7039 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007040 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007041 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7042 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007043 }
7044 }
7045
7046 @Override
7047 public void saveANRState(String reason) {
7048 synchronized (mGlobalLock) {
7049 final StringWriter sw = new StringWriter();
7050 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7051 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7052 if (reason != null) {
7053 pw.println(" Reason: " + reason);
7054 }
7055 pw.println();
7056 getActivityStartController().dump(pw, " ", null);
7057 pw.println();
7058 pw.println("-------------------------------------------------------------------------------");
7059 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7060 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7061 "" /* header */);
7062 pw.println();
7063 pw.close();
7064
7065 mLastANRState = sw.toString();
7066 }
7067 }
7068
7069 @Override
7070 public void clearSavedANRState() {
7071 synchronized (mGlobalLock) {
7072 mLastANRState = null;
7073 }
7074 }
7075
7076 @Override
7077 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7078 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7079 synchronized (mGlobalLock) {
7080 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7081 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7082 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7083 dumpLastANRLocked(pw);
7084 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7085 dumpLastANRTracesLocked(pw);
7086 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7087 dumpActivityStarterLocked(pw, dumpPackage);
7088 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7089 dumpActivityContainersLocked(pw);
7090 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7091 if (getRecentTasks() != null) {
7092 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7093 }
7094 }
7095 }
7096 }
7097
7098 @Override
7099 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7100 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7101 int wakefulness) {
7102 synchronized (mGlobalLock) {
7103 if (mHomeProcess != null && (dumpPackage == null
7104 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7105 if (needSep) {
7106 pw.println();
7107 needSep = false;
7108 }
7109 pw.println(" mHomeProcess: " + mHomeProcess);
7110 }
7111 if (mPreviousProcess != null && (dumpPackage == null
7112 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7113 if (needSep) {
7114 pw.println();
7115 needSep = false;
7116 }
7117 pw.println(" mPreviousProcess: " + mPreviousProcess);
7118 }
7119 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7120 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7121 StringBuilder sb = new StringBuilder(128);
7122 sb.append(" mPreviousProcessVisibleTime: ");
7123 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7124 pw.println(sb);
7125 }
7126 if (mHeavyWeightProcess != null && (dumpPackage == null
7127 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7128 if (needSep) {
7129 pw.println();
7130 needSep = false;
7131 }
7132 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7133 }
7134 if (dumpPackage == null) {
7135 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007136 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 }
7138 if (dumpAll) {
7139 if (dumpPackage == null) {
7140 pw.println(" mConfigWillChange: "
7141 + getTopDisplayFocusedStack().mConfigWillChange);
7142 }
7143 if (mCompatModePackages.getPackages().size() > 0) {
7144 boolean printed = false;
7145 for (Map.Entry<String, Integer> entry
7146 : mCompatModePackages.getPackages().entrySet()) {
7147 String pkg = entry.getKey();
7148 int mode = entry.getValue();
7149 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7150 continue;
7151 }
7152 if (!printed) {
7153 pw.println(" mScreenCompatPackages:");
7154 printed = true;
7155 }
7156 pw.println(" " + pkg + ": " + mode);
7157 }
7158 }
7159 }
7160
7161 if (dumpPackage == null) {
7162 pw.println(" mWakefulness="
7163 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007164 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007165 if (mRunningVoice != null) {
7166 pw.println(" mRunningVoice=" + mRunningVoice);
7167 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7168 }
7169 pw.println(" mSleeping=" + mSleeping);
7170 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7171 pw.println(" mVrController=" + mVrController);
7172 }
7173 if (mCurAppTimeTracker != null) {
7174 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7175 }
7176 if (mAllowAppSwitchUids.size() > 0) {
7177 boolean printed = false;
7178 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7179 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7180 for (int j = 0; j < types.size(); j++) {
7181 if (dumpPackage == null ||
7182 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7183 if (needSep) {
7184 pw.println();
7185 needSep = false;
7186 }
7187 if (!printed) {
7188 pw.println(" mAllowAppSwitchUids:");
7189 printed = true;
7190 }
7191 pw.print(" User ");
7192 pw.print(mAllowAppSwitchUids.keyAt(i));
7193 pw.print(": Type ");
7194 pw.print(types.keyAt(j));
7195 pw.print(" = ");
7196 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7197 pw.println();
7198 }
7199 }
7200 }
7201 }
7202 if (dumpPackage == null) {
7203 if (mController != null) {
7204 pw.println(" mController=" + mController
7205 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7206 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007207 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7208 pw.println(" mLaunchingActivityWakeLock="
7209 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007210 }
7211
7212 return needSep;
7213 }
7214 }
7215
7216 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007217 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7218 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 synchronized (mGlobalLock) {
7220 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007221 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007223 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7224 if (mRunningVoice != null) {
7225 final long vrToken = proto.start(
7226 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7227 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7228 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007229 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007230 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7231 proto.end(vrToken);
7232 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007233 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007234 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007235 if (mController != null) {
7236 final long token = proto.start(CONTROLLER);
7237 proto.write(CONTROLLER, mController.toString());
7238 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7239 proto.end(token);
7240 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007241 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7242 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007243 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245
7246 if (mHomeProcess != null && (dumpPackage == null
7247 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007248 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007249 }
7250
7251 if (mPreviousProcess != null && (dumpPackage == null
7252 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007253 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007254 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7255 }
7256
7257 if (mHeavyWeightProcess != null && (dumpPackage == null
7258 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007259 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007260 }
7261
7262 for (Map.Entry<String, Integer> entry
7263 : mCompatModePackages.getPackages().entrySet()) {
7264 String pkg = entry.getKey();
7265 int mode = entry.getValue();
7266 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7267 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7268 proto.write(PACKAGE, pkg);
7269 proto.write(MODE, mode);
7270 proto.end(compatToken);
7271 }
7272 }
7273
7274 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007275 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007276 }
7277
7278 }
7279 }
7280
7281 @Override
7282 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7283 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7284 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007285 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7286 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007287 }
7288
7289 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007290 public void dumpForOom(PrintWriter pw) {
7291 synchronized (mGlobalLock) {
7292 pw.println(" mHomeProcess: " + mHomeProcess);
7293 pw.println(" mPreviousProcess: " + mPreviousProcess);
7294 if (mHeavyWeightProcess != null) {
7295 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7296 }
7297 }
7298 }
7299
7300 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007301 public boolean canGcNow() {
7302 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007303 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007304 }
7305 }
7306
Riddle Hsua0536432019-02-16 00:38:59 +08007307 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007308 @Override
7309 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007310 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007311 if (mRootWindowContainer == null) {
7312 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007313 // oomadj after AMS created.
7314 return null;
7315 }
Louis Chang149d5c82019-12-30 09:47:39 +08007316 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007317 return top != null ? top.app : null;
7318 }
7319 }
7320
Riddle Hsua0536432019-02-16 00:38:59 +08007321 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007322 @Override
7323 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007324 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007325 if (mRootWindowContainer != null) {
7326 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007327 }
7328 }
7329 }
7330
7331 @Override
7332 public void scheduleDestroyAllActivities(String reason) {
7333 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007334 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007335 }
7336 }
7337
7338 @Override
7339 public void removeUser(int userId) {
7340 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007341 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007342 }
7343 }
7344
7345 @Override
7346 public boolean switchUser(int userId, UserState userState) {
7347 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007348 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007349 }
7350 }
7351
7352 @Override
7353 public void onHandleAppCrash(WindowProcessController wpc) {
7354 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007355 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007356 }
7357 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007358
7359 @Override
7360 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7361 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007362 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007363 }
7364 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007365
Riddle Hsua0536432019-02-16 00:38:59 +08007366 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007367 @Override
7368 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007369 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007370 }
7371
Riddle Hsua0536432019-02-16 00:38:59 +08007372 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007373 @Override
7374 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007375 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007376 }
7377
Riddle Hsua0536432019-02-16 00:38:59 +08007378 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007379 @Override
7380 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007381 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007382 }
7383
Riddle Hsua0536432019-02-16 00:38:59 +08007384 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007385 @Override
7386 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007387 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007388 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007389
7390 @Override
7391 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007392 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007393 mPendingTempWhitelist.put(uid, tag);
7394 }
7395 }
7396
7397 @Override
7398 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007399 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007400 mPendingTempWhitelist.remove(uid);
7401 }
7402 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007403
7404 @Override
7405 public boolean handleAppCrashInActivityController(String processName, int pid,
7406 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7407 Runnable killCrashingAppCallback) {
7408 synchronized (mGlobalLock) {
7409 if (mController == null) {
7410 return false;
7411 }
7412
7413 try {
7414 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7415 stackTrace)) {
7416 killCrashingAppCallback.run();
7417 return true;
7418 }
7419 } catch (RemoteException e) {
7420 mController = null;
7421 Watchdog.getInstance().setActivityController(null);
7422 }
7423 return false;
7424 }
7425 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007426
7427 @Override
7428 public void removeRecentTasksByPackageName(String packageName, int userId) {
7429 synchronized (mGlobalLock) {
7430 mRecentTasks.removeTasksByPackageName(packageName, userId);
7431 }
7432 }
7433
7434 @Override
7435 public void cleanupRecentTasksForUser(int userId) {
7436 synchronized (mGlobalLock) {
7437 mRecentTasks.cleanupLocked(userId);
7438 }
7439 }
7440
7441 @Override
7442 public void loadRecentTasksForUser(int userId) {
7443 synchronized (mGlobalLock) {
7444 mRecentTasks.loadUserRecentsLocked(userId);
7445 }
7446 }
7447
7448 @Override
7449 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7450 synchronized (mGlobalLock) {
7451 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7452 }
7453 }
7454
7455 @Override
7456 public void flushRecentTasks() {
7457 mRecentTasks.flush();
7458 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007459
7460 @Override
7461 public WindowProcessController getHomeProcess() {
7462 synchronized (mGlobalLock) {
7463 return mHomeProcess;
7464 }
7465 }
7466
7467 @Override
7468 public WindowProcessController getPreviousProcess() {
7469 synchronized (mGlobalLock) {
7470 return mPreviousProcess;
7471 }
7472 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007473
7474 @Override
7475 public void clearLockedTasks(String reason) {
7476 synchronized (mGlobalLock) {
7477 getLockTaskController().clearLockedTasks(reason);
7478 }
7479 }
7480
7481 @Override
7482 public void updateUserConfiguration() {
7483 synchronized (mGlobalLock) {
7484 final Configuration configuration = new Configuration(getGlobalConfiguration());
7485 final int currentUserId = mAmInternal.getCurrentUserId();
7486 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7487 configuration, currentUserId, Settings.System.canWrite(mContext));
7488 updateConfigurationLocked(configuration, null /* starting */,
7489 false /* initLocale */, false /* persistent */, currentUserId,
7490 false /* deferResume */);
7491 }
7492 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007493
7494 @Override
7495 public boolean canShowErrorDialogs() {
7496 synchronized (mGlobalLock) {
7497 return mShowDialogs && !mSleeping && !mShuttingDown
7498 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7499 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7500 mAmInternal.getCurrentUserId())
7501 && !(UserManager.isDeviceInDemoMode(mContext)
7502 && mAmInternal.getCurrentUser().isDemo());
7503 }
7504 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007505
7506 @Override
7507 public void setProfileApp(String profileApp) {
7508 synchronized (mGlobalLock) {
7509 mProfileApp = profileApp;
7510 }
7511 }
7512
7513 @Override
7514 public void setProfileProc(WindowProcessController wpc) {
7515 synchronized (mGlobalLock) {
7516 mProfileProc = wpc;
7517 }
7518 }
7519
7520 @Override
7521 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7522 synchronized (mGlobalLock) {
7523 mProfilerInfo = profilerInfo;
7524 }
7525 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007526
7527 @Override
7528 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7529 synchronized (mGlobalLock) {
7530 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7531 }
7532 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007533
7534 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007535 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7536 boolean reducedResolution) {
7537 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7538 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007539 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007540
7541 @Override
7542 public boolean isUidForeground(int uid) {
7543 synchronized (mGlobalLock) {
7544 return ActivityTaskManagerService.this.isUidForeground(uid);
7545 }
7546 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007547
7548 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007549 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007550 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007551 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007552 }
7553 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007554
7555 @Override
7556 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007557 // Translate package names into UIDs
7558 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007559 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007560 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7561 if (uid >= 0) {
7562 result.add(uid);
7563 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007564 }
7565 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007566 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007567 }
7568 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007569 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007570}