blob: 76c0e4eeecae6d9cfc199af627c1d1ef63240e4d [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;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700231import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700239import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700242import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
243import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700245import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.internal.policy.IKeyguardDismissCallback;
247import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700248import com.android.internal.util.ArrayUtils;
249import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700250import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
261import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900268import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700295import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700347 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700348
Wale Ogunwalef6733932018-06-27 05:14:34 -0700349 /**
350 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
351 * change at runtime. Use mContext for non-UI purposes.
352 */
353 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700354 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700357 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700358 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700359 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800360 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800361 @VisibleForTesting
362 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700363 PowerManagerInternal mPowerManagerInternal;
364 private UsageStatsManagerInternal mUsageStatsInternal;
365
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700366 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700367 IntentFirewall mIntentFirewall;
368
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700369 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800370 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800371 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700372 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800373 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
374 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
375 *
376 * @see WindowManagerThreadPriorityBooster
377 */
378 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700379 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800380 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700381 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700382 private UserManagerService mUserManager;
383 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700384 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800385 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700386 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700387 /** All processes currently running that might have a window organized by name. */
388 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100389 /** All processes we currently have running mapped by pid and uid */
390 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /** This is the process holding what we currently consider to be the "home" activity. */
392 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700393 /** The currently running heavy-weight process, if any. */
394 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700395 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700396 /**
397 * This is the process holding the activity the user last visited that is in a different process
398 * from the one they are currently in.
399 */
400 WindowProcessController mPreviousProcess;
401 /** The time at which the previous process was last visible. */
402 long mPreviousProcessVisibleTime;
403
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700404 /** List of intents that were used to start the most recent tasks. */
405 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700406 /** State of external calls telling us if the device is awake or asleep. */
407 private boolean mKeyguardShown = false;
408
409 // Wrapper around VoiceInteractionServiceManager
410 private AssistUtils mAssistUtils;
411
412 // VoiceInteraction session ID that changes for each new request except when
413 // being called for multi-window assist in a single session.
414 private int mViSessionId = 1000;
415
416 // How long to wait in getAssistContextExtras for the activity and foreground services
417 // to respond with the result.
418 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
419
420 // How long top wait when going through the modern assist (which doesn't need to block
421 // on getting this result before starting to launch its UI).
422 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
423
424 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
425 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
426
Alison Cichowlas3e340502018-08-07 17:15:01 -0400427 // Permission tokens are used to temporarily granted a trusted app the ability to call
428 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
429 // showing any appropriate error messages to the user.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
431 10 * MINUTE_IN_MILLIS;
432
433 // How long before the service actually expires a token. This is slightly longer than
434 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
435 // expiration exception.
436 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
437 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
438
439 // How long the service will remember expired tokens, for the purpose of providing error
440 // messaging when a client uses an expired token.
441 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
442 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
443
444 // Activity tokens of system activities that are delegating their call to
445 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
446 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
447
448 // Permission tokens that have expired, but we remember for error reporting.
449 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
450
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700451 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
452
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 // Keeps track of the active voice interaction service component, notified from
454 // VoiceInteractionManagerService
455 ComponentName mActiveVoiceInteractionServiceComponent;
456
Michal Karpinskida34cd42019-04-02 19:46:52 +0100457 // A map userId and all its companion app uids
458 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000459
Wale Ogunwalee2172292018-10-25 10:11:10 -0700460 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461 KeyguardController mKeyguardController;
462 private final ClientLifecycleManager mLifecycleManager;
463 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700464 /** The controller for all operations related to locktask. */
465 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700466 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700467
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 boolean mSuppressResizeConfigChanges;
469
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700470 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700471 new UpdateConfigurationResult();
472
473 static final class UpdateConfigurationResult {
474 // Configuration changes that were updated.
475 int changes;
476 // If the activity was relaunched to match the new configuration.
477 boolean activityRelaunched;
478
479 void reset() {
480 changes = 0;
481 activityRelaunched = false;
482 }
483 }
484
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700485 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 private int mConfigurationSeq;
487 // To cache the list of supported system locales
488 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700489
490 /**
491 * Temp object used when global and/or display override configuration is updated. It is also
492 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
493 * anyone...
494 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 private Configuration mTempConfig = new Configuration();
496
Wale Ogunwalef6733932018-06-27 05:14:34 -0700497 /** Temporary to avoid allocations. */
498 final StringBuilder mStringBuilder = new StringBuilder(256);
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 // Amount of time after a call to stopAppSwitches() during which we will
501 // prevent further untrusted switches from happening.
502 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
503
504 /**
505 * The time at which we will allow normal application switches again,
506 * after a call to {@link #stopAppSwitches()}.
507 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700508 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700509 /**
510 * This is set to true after the first switch after mAppSwitchesAllowedTime
511 * is set; any switches after that will clear the time.
512 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700513 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700514
Ricky Wai906af482019-06-03 17:25:28 +0100515 /**
516 * Last stop app switches time, apps finished before this time cannot start background activity
517 * even if they are in grace period.
518 */
519 private long mLastStopAppSwitchesTime;
520
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521 IActivityController mController = null;
522 boolean mControllerIsAMonkey = false;
523
Wale Ogunwale214f3482018-10-04 11:00:47 -0700524 final int mFactoryTest;
525
526 /** Used to control how we initialize the service. */
527 ComponentName mTopComponent;
528 String mTopAction = Intent.ACTION_MAIN;
529 String mTopData;
530
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800531 /** Profiling app information. */
532 String mProfileApp = null;
533 WindowProcessController mProfileProc = null;
534 ProfilerInfo mProfilerInfo = null;
535
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700536 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700537 * Dump of the activity state at the time of the last ANR. Cleared after
538 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
539 */
540 String mLastANRState;
541
542 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543 * Used to retain an update lock when the foreground activity is in
544 * immersive mode.
545 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700546 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700547
548 /**
549 * Packages that are being allowed to perform unrestricted app switches. Mapping is
550 * User -> Type -> uid.
551 */
552 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
553
554 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700555 private int mThumbnailWidth;
556 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700557
558 /**
559 * Flag that indicates if multi-window is enabled.
560 *
561 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
562 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
563 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
564 * At least one of the forms of multi-window must be enabled in order for this flag to be
565 * initialized to 'true'.
566 *
567 * @see #mSupportsSplitScreenMultiWindow
568 * @see #mSupportsFreeformWindowManagement
569 * @see #mSupportsPictureInPicture
570 * @see #mSupportsMultiDisplay
571 */
572 boolean mSupportsMultiWindow;
573 boolean mSupportsSplitScreenMultiWindow;
574 boolean mSupportsFreeformWindowManagement;
575 boolean mSupportsPictureInPicture;
576 boolean mSupportsMultiDisplay;
577 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700578 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700579
580 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
581
582 // VR Vr2d Display Id.
583 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700584
Wale Ogunwalef6733932018-06-27 05:14:34 -0700585 /**
586 * Set while we are wanting to sleep, to prevent any
587 * activities from being started/resumed.
588 *
589 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
590 *
591 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
592 * while in the sleep state until there is a pending transition out of sleep, in which case
593 * mSleeping is set to false, and remains false while awake.
594 *
595 * Whether mSleeping can quickly toggled between true/false without the device actually
596 * display changing states is undefined.
597 */
598 private boolean mSleeping = false;
599
600 /**
601 * The process state used for processes that are running the top activities.
602 * This changes between TOP and TOP_SLEEPING to following mSleeping.
603 */
604 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
605
Riddle Hsua0022cd2019-09-09 21:12:41 +0800606 @Retention(RetentionPolicy.SOURCE)
607 @IntDef({
608 LAYOUT_REASON_CONFIG_CHANGED,
609 LAYOUT_REASON_VISIBILITY_CHANGED,
610 })
611 @interface LayoutReason {}
612 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
613 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
614
615 /** The reasons to perform surface placement. */
616 @LayoutReason
617 private int mLayoutReasons;
618
Wale Ogunwalef6733932018-06-27 05:14:34 -0700619 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
620 // automatically. Important for devices without direct input devices.
621 private boolean mShowDialogs = true;
622
623 /** Set if we are shutting down the system, similar to sleeping. */
624 boolean mShuttingDown = false;
625
626 /**
627 * We want to hold a wake lock while running a voice interaction session, since
628 * this may happen with the screen off and we need to keep the CPU running to
629 * be able to continue to interact with the user.
630 */
631 PowerManager.WakeLock mVoiceWakeLock;
632
633 /**
634 * Set while we are running a voice interaction. This overrides sleeping while it is active.
635 */
636 IVoiceInteractionSession mRunningVoice;
637
638 /**
639 * The last resumed activity. This is identical to the current resumed activity most
640 * of the time but could be different when we're pausing one activity before we resume
641 * another activity.
642 */
643 ActivityRecord mLastResumedActivity;
644
645 /**
646 * The activity that is currently being traced as the active resumed activity.
647 *
648 * @see #updateResumedAppTrace
649 */
650 private @Nullable ActivityRecord mTracedResumedActivity;
651
652 /** If non-null, we are tracking the time the user spends in the currently focused app. */
653 AppTimeTracker mCurAppTimeTracker;
654
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700655 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700656
Wale Ogunwale53783742018-09-16 10:21:51 -0700657 /**
658 * Packages that the user has asked to have run in screen size
659 * compatibility mode instead of filling the screen.
660 */
661 CompatModePackages mCompatModePackages;
662
Wale Ogunwalef6733932018-06-27 05:14:34 -0700663 private FontScaleSettingObserver mFontScaleSettingObserver;
664
Ricky Wai96f5c352019-04-10 18:40:17 +0100665 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000666
Wale Ogunwalef6733932018-06-27 05:14:34 -0700667 private final class FontScaleSettingObserver extends ContentObserver {
668 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
669 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
670
671 public FontScaleSettingObserver() {
672 super(mH);
673 final ContentResolver resolver = mContext.getContentResolver();
674 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
675 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
676 UserHandle.USER_ALL);
677 }
678
679 @Override
680 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
681 if (mFontScaleUri.equals(uri)) {
682 updateFontScaleIfNeeded(userId);
683 } else if (mHideErrorDialogsUri.equals(uri)) {
684 synchronized (mGlobalLock) {
685 updateShouldShowDialogsLocked(getGlobalConfiguration());
686 }
687 }
688 }
689 }
690
Riddle Hsua0536432019-02-16 00:38:59 +0800691 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
692 @Target(ElementType.METHOD)
693 @Retention(RetentionPolicy.SOURCE)
694 @interface HotPath {
695 int NONE = 0;
696 int OOM_ADJUSTMENT = 1;
697 int LRU_UPDATE = 2;
698 int PROCESS_CHANGE = 3;
699 int caller() default NONE;
700 }
701
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800702 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
703 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900704 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800705 mAmInternal.updateOomAdj();
706 }
707 };
708
Charles Chen8d98dd22018-12-26 17:36:54 +0800709 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
710 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700711 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700712 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700713 mSystemThread = ActivityThread.currentActivityThread();
714 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700715 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800716 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700717 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700718 }
719
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700720 public void onSystemReady() {
721 synchronized (mGlobalLock) {
722 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
723 PackageManager.FEATURE_CANT_SAVE_STATE);
724 mAssistUtils = new AssistUtils(mContext);
725 mVrController.onSystemReady();
726 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700727 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700728 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700729 }
730
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700731 public void onInitPowerManagement() {
732 synchronized (mGlobalLock) {
733 mStackSupervisor.initPowerManagement();
734 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
735 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
736 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
737 mVoiceWakeLock.setReferenceCounted(false);
738 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700739 }
740
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700741 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700742 mFontScaleSettingObserver = new FontScaleSettingObserver();
743 }
744
Wale Ogunwale59507092018-10-29 09:00:30 -0700745 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700746 final boolean freeformWindowManagement =
747 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
748 || Settings.Global.getInt(
749 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
750
751 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
752 final boolean supportsPictureInPicture = supportsMultiWindow &&
753 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
754 final boolean supportsSplitScreenMultiWindow =
755 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
756 final boolean supportsMultiDisplay = mContext.getPackageManager()
757 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
759 final boolean forceResizable = Settings.Global.getInt(
760 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700761 final boolean sizeCompatFreeform = Settings.Global.getInt(
762 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700763
764 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900765 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766
767 final Configuration configuration = new Configuration();
768 Settings.System.getConfiguration(resolver, configuration);
769 if (forceRtl) {
770 // This will take care of setting the correct layout direction flags
771 configuration.setLayoutDirection(configuration.locale);
772 }
773
774 synchronized (mGlobalLock) {
775 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700776 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700777 final boolean multiWindowFormEnabled = freeformWindowManagement
778 || supportsSplitScreenMultiWindow
779 || supportsPictureInPicture
780 || supportsMultiDisplay;
781 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
782 mSupportsMultiWindow = true;
783 mSupportsFreeformWindowManagement = freeformWindowManagement;
784 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
785 mSupportsPictureInPicture = supportsPictureInPicture;
786 mSupportsMultiDisplay = supportsMultiDisplay;
787 } else {
788 mSupportsMultiWindow = false;
789 mSupportsFreeformWindowManagement = false;
790 mSupportsSplitScreenMultiWindow = false;
791 mSupportsPictureInPicture = false;
792 mSupportsMultiDisplay = false;
793 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700794 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700795 // This happens before any activities are started, so we can change global configuration
796 // in-place.
797 updateConfigurationLocked(configuration, null, true);
798 final Configuration globalConfig = getGlobalConfiguration();
799 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
800
801 // Load resources only after the current configuration has been set.
802 final Resources res = mContext.getResources();
803 mThumbnailWidth = res.getDimensionPixelSize(
804 com.android.internal.R.dimen.thumbnail_width);
805 mThumbnailHeight = res.getDimensionPixelSize(
806 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700807 }
808 }
809
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800810 public WindowManagerGlobalLock getGlobalLock() {
811 return mGlobalLock;
812 }
813
Yunfan Chen585f2932019-01-29 16:04:45 +0900814 /** For test purpose only. */
815 @VisibleForTesting
816 public ActivityTaskManagerInternal getAtmInternal() {
817 return mInternal;
818 }
819
Riddle Hsud93a6c42018-11-29 21:50:06 +0800820 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
821 Looper looper) {
822 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700823 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700824 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700825 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800826 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700827 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700828 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700830
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700831 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700832 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700833 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700834 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700835 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700836 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700837 mKeyguardController = mStackSupervisor.getKeyguardController();
838 }
839
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700840 public void onActivityManagerInternalAdded() {
841 synchronized (mGlobalLock) {
842 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
843 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
844 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700845 }
846
Yunfan Chen75157d72018-07-27 14:47:21 +0900847 int increaseConfigurationSeqLocked() {
848 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
849 return mConfigurationSeq;
850 }
851
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700852 protected ActivityStackSupervisor createStackSupervisor() {
853 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
854 supervisor.initialize();
855 return supervisor;
856 }
857
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800858 protected AppWarnings createAppWarnings(
859 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
860 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
861 }
862
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700863 public void setWindowManager(WindowManagerService wm) {
864 synchronized (mGlobalLock) {
865 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800866 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800867 mTempConfig.setToDefaults();
868 mTempConfig.setLocales(LocaleList.getDefault());
869 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800870 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700871 mLockTaskController.setWindowManager(wm);
872 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800873 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700875 }
876
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
878 synchronized (mGlobalLock) {
879 mUsageStatsInternal = usageStatsManager;
880 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700881 }
882
Wale Ogunwalef6733932018-06-27 05:14:34 -0700883 UserManagerService getUserManager() {
884 if (mUserManager == null) {
885 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
886 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
887 }
888 return mUserManager;
889 }
890
891 AppOpsService getAppOpsService() {
892 if (mAppOpsService == null) {
893 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
894 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
895 }
896 return mAppOpsService;
897 }
898
899 boolean hasUserRestriction(String restriction, int userId) {
900 return getUserManager().hasUserRestriction(restriction, userId);
901 }
902
Michal Karpinski15486842019-04-25 17:33:42 +0100903 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
904 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800905 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100906 if (mode == AppOpsManager.MODE_DEFAULT) {
907 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
908 == PERMISSION_GRANTED;
909 }
910 return mode == AppOpsManager.MODE_ALLOWED;
911 }
912
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700913 @VisibleForTesting
914 protected void setRecentTasks(RecentTasks recentTasks) {
915 mRecentTasks = recentTasks;
916 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700917 }
918
919 RecentTasks getRecentTasks() {
920 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700921 }
922
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700923 ClientLifecycleManager getLifecycleManager() {
924 return mLifecycleManager;
925 }
926
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700927 ActivityStartController getActivityStartController() {
928 return mActivityStartController;
929 }
930
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700931 TaskChangeNotificationController getTaskChangeNotificationController() {
932 return mTaskChangeNotificationController;
933 }
934
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700935 LockTaskController getLockTaskController() {
936 return mLockTaskController;
937 }
938
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 /**
940 * Return the global configuration used by the process corresponding to the input pid. This is
941 * usually the global configuration with some overrides specific to that process.
942 */
943 Configuration getGlobalConfigurationForCallingPid() {
944 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800945 return getGlobalConfigurationForPid(pid);
946 }
947
948 /**
949 * Return the global configuration used by the process corresponding to the given pid.
950 */
951 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900952 if (pid == MY_PID || pid < 0) {
953 return getGlobalConfiguration();
954 }
955 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100956 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 return app != null ? app.getConfiguration() : getGlobalConfiguration();
958 }
959 }
960
961 /**
962 * Return the device configuration info used by the process corresponding to the input pid.
963 * The value is consistent with the global configuration for the process.
964 */
965 @Override
966 public ConfigurationInfo getDeviceConfigurationInfo() {
967 ConfigurationInfo config = new ConfigurationInfo();
968 synchronized (mGlobalLock) {
969 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
970 config.reqTouchScreen = globalConfig.touchscreen;
971 config.reqKeyboardType = globalConfig.keyboard;
972 config.reqNavigation = globalConfig.navigation;
973 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
974 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
975 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
976 }
977 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
978 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
979 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
980 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700981 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900982 }
983 return config;
984 }
985
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700987 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public static final class Lifecycle extends SystemService {
991 private final ActivityTaskManagerService mService;
992
993 public Lifecycle(Context context) {
994 super(context);
995 mService = new ActivityTaskManagerService(context);
996 }
997
998 @Override
999 public void onStart() {
1000 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001001 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 }
1003
Garfield Tan891146c2018-10-09 12:14:00 -07001004 @Override
1005 public void onUnlockUser(int userId) {
1006 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001007 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001008 }
1009 }
1010
1011 @Override
1012 public void onCleanupUser(int userId) {
1013 synchronized (mService.getGlobalLock()) {
1014 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1015 }
1016 }
1017
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001018 public ActivityTaskManagerService getService() {
1019 return mService;
1020 }
1021 }
1022
1023 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 public final int startActivity(IApplicationThread caller, String callingPackage,
1025 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1026 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1027 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1028 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1029 UserHandle.getCallingUserId());
1030 }
1031
1032 @Override
1033 public final int startActivities(IApplicationThread caller, String callingPackage,
1034 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1035 int userId) {
1036 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 enforceNotIsolatedCaller(reason);
1038 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001040 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1041 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1042 reason, null /* originatingPendingIntent */,
1043 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 }
1045
1046 @Override
1047 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1048 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1049 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1050 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1051 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1052 true /*validateIncomingUser*/);
1053 }
1054
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001055 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1057 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1058 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001059 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001061 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1063
1064 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001065 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .setCaller(caller)
1067 .setCallingPackage(callingPackage)
1068 .setResolvedType(resolvedType)
1069 .setResultTo(resultTo)
1070 .setResultWho(resultWho)
1071 .setRequestCode(requestCode)
1072 .setStartFlags(startFlags)
1073 .setProfilerInfo(profilerInfo)
1074 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001075 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 .execute();
1077
1078 }
1079
1080 @Override
1081 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1082 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1084 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 // Refuse possible leaked file descriptors
1086 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089
1090 if (!(target instanceof PendingIntentRecord)) {
1091 throw new IllegalArgumentException("Bad PendingIntent object");
1092 }
1093
1094 PendingIntentRecord pir = (PendingIntentRecord)target;
1095
1096 synchronized (mGlobalLock) {
1097 // If this is coming from the currently resumed activity, it is
1098 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001099 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001100 if (stack.mResumedActivity != null &&
1101 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001102 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 }
1104 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001105 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 }
1108
1109 @Override
1110 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1111 Bundle bOptions) {
1112 // Refuse possible leaked file descriptors
1113 if (intent != null && intent.hasFileDescriptors()) {
1114 throw new IllegalArgumentException("File descriptors passed in Intent");
1115 }
1116 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1117
1118 synchronized (mGlobalLock) {
1119 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1120 if (r == null) {
1121 SafeActivityOptions.abort(options);
1122 return false;
1123 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 // The caller is not running... d'oh!
1126 SafeActivityOptions.abort(options);
1127 return false;
1128 }
1129 intent = new Intent(intent);
1130 // The caller is not allowed to change the data.
1131 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1132 // And we are resetting to find the next component...
1133 intent.setComponent(null);
1134
1135 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1136
1137 ActivityInfo aInfo = null;
1138 try {
1139 List<ResolveInfo> resolves =
1140 AppGlobals.getPackageManager().queryIntentActivities(
1141 intent, r.resolvedType,
1142 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1143 UserHandle.getCallingUserId()).getList();
1144
1145 // Look for the original activity in the list...
1146 final int N = resolves != null ? resolves.size() : 0;
1147 for (int i=0; i<N; i++) {
1148 ResolveInfo rInfo = resolves.get(i);
1149 if (rInfo.activityInfo.packageName.equals(r.packageName)
1150 && rInfo.activityInfo.name.equals(r.info.name)) {
1151 // We found the current one... the next matching is
1152 // after it.
1153 i++;
1154 if (i<N) {
1155 aInfo = resolves.get(i).activityInfo;
1156 }
1157 if (debug) {
1158 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1159 + "/" + r.info.name);
1160 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1161 ? "null" : aInfo.packageName + "/" + aInfo.name));
1162 }
1163 break;
1164 }
1165 }
1166 } catch (RemoteException e) {
1167 }
1168
1169 if (aInfo == null) {
1170 // Nobody who is next!
1171 SafeActivityOptions.abort(options);
1172 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1173 return false;
1174 }
1175
1176 intent.setComponent(new ComponentName(
1177 aInfo.applicationInfo.packageName, aInfo.name));
1178 intent.setFlags(intent.getFlags()&~(
1179 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1180 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1181 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1182 FLAG_ACTIVITY_NEW_TASK));
1183
1184 // Okay now we need to start the new activity, replacing the currently running activity.
1185 // This is a little tricky because we want to start the new one as if the current one is
1186 // finished, but not finish the current one first so that there is no flicker.
1187 // And thus...
1188 final boolean wasFinishing = r.finishing;
1189 r.finishing = true;
1190
1191 // Propagate reply information over to the new activity.
1192 final ActivityRecord resultTo = r.resultTo;
1193 final String resultWho = r.resultWho;
1194 final int requestCode = r.requestCode;
1195 r.resultTo = null;
1196 if (resultTo != null) {
1197 resultTo.removeResultsLocked(r, resultWho, requestCode);
1198 }
1199
1200 final long origId = Binder.clearCallingIdentity();
1201 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001202 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001203 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001204 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001205 .setResolvedType(r.resolvedType)
1206 .setActivityInfo(aInfo)
1207 .setResultTo(resultTo != null ? resultTo.appToken : null)
1208 .setResultWho(resultWho)
1209 .setRequestCode(requestCode)
1210 .setCallingPid(-1)
1211 .setCallingUid(r.launchedFromUid)
1212 .setCallingPackage(r.launchedFromPackage)
1213 .setRealCallingPid(-1)
1214 .setRealCallingUid(r.launchedFromUid)
1215 .setActivityOptions(options)
1216 .execute();
1217 Binder.restoreCallingIdentity(origId);
1218
1219 r.finishing = wasFinishing;
1220 if (res != ActivityManager.START_SUCCESS) {
1221 return false;
1222 }
1223 return true;
1224 }
1225 }
1226
1227 @Override
1228 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1231 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001232 enforceNotIsolatedCaller("startActivityAndWait");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1234 userId, "startActivityAndWait");
1235 // TODO: Switch to user app stacks here.
1236 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setActivityOptions(bOptions)
1245 .setUserId(userId)
1246 .setProfilerInfo(profilerInfo)
1247 .setWaitResult(res)
1248 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001249 return res;
1250 }
1251
1252 @Override
1253 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1254 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1255 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001256 enforceNotIsolatedCaller("startActivityWithConfig");
1257 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1258 "startActivityWithConfig");
1259 // TODO: Switch to user app stacks here.
1260 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1261 .setCaller(caller)
1262 .setCallingPackage(callingPackage)
1263 .setResolvedType(resolvedType)
1264 .setResultTo(resultTo)
1265 .setResultWho(resultWho)
1266 .setRequestCode(requestCode)
1267 .setStartFlags(startFlags)
1268 .setGlobalConfiguration(config)
1269 .setActivityOptions(bOptions)
1270 .setUserId(userId)
1271 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001272 }
1273
Alison Cichowlas3e340502018-08-07 17:15:01 -04001274
1275 @Override
1276 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1277 int callingUid = Binder.getCallingUid();
1278 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1279 throw new SecurityException("Only the system process can request a permission token, "
1280 + "received request from uid: " + callingUid);
1281 }
1282 IBinder permissionToken = new Binder();
1283 synchronized (mGlobalLock) {
1284 mStartActivitySources.put(permissionToken, delegatorToken);
1285 }
1286
1287 Message expireMsg = PooledLambda.obtainMessage(
1288 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1289 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1290
1291 Message forgetMsg = PooledLambda.obtainMessage(
1292 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1293 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1294
1295 return permissionToken;
1296 }
1297
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 @Override
1299 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1300 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001301 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1302 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001303 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001304 // permission grants) as any app that may launch one of your own activities. So we only
1305 // allow this in two cases:
1306 // 1) The caller is an activity that is part of the core framework, and then only when it
1307 // is running as the system.
1308 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1309 // can only be requested by a system activity, which may then delegate this call to
1310 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 final ActivityRecord sourceRecord;
1312 final int targetUid;
1313 final String targetPackage;
1314 final boolean isResolver;
1315 synchronized (mGlobalLock) {
1316 if (resultTo == null) {
1317 throw new SecurityException("Must be called from an activity");
1318 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319 final IBinder sourceToken;
1320 if (permissionToken != null) {
1321 // To even attempt to use a permissionToken, an app must also have this signature
1322 // permission.
1323 mAmInternal.enforceCallingPermission(
1324 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1325 "startActivityAsCaller");
1326 // If called with a permissionToken, we want the sourceRecord from the delegator
1327 // activity that requested this token.
1328 sourceToken = mStartActivitySources.remove(permissionToken);
1329 if (sourceToken == null) {
1330 // Invalid permissionToken, check if it recently expired.
1331 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1332 throw new SecurityException("Called with expired permission token: "
1333 + permissionToken);
1334 } else {
1335 throw new SecurityException("Called with invalid permission token: "
1336 + permissionToken);
1337 }
1338 }
1339 } else {
1340 // This method was called directly by the source.
1341 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001343
Louis Chang149d5c82019-12-30 09:47:39 +08001344 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345 if (sourceRecord == null) {
1346 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 }
1348 if (sourceRecord.app == null) {
1349 throw new SecurityException("Called without a process attached to activity");
1350 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001351
1352 // Whether called directly or from a delegate, the source activity must be from the
1353 // android package.
1354 if (!sourceRecord.info.packageName.equals("android")) {
1355 throw new SecurityException("Must be called from an activity that is "
1356 + "declared in the android package");
1357 }
1358
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001359 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 // This is still okay, as long as this activity is running under the
1361 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001364 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 + " must be system uid or original calling uid "
1366 + sourceRecord.launchedFromUid);
1367 }
1368 }
1369 if (ignoreTargetSecurity) {
1370 if (intent.getComponent() == null) {
1371 throw new SecurityException(
1372 "Component must be specified with ignoreTargetSecurity");
1373 }
1374 if (intent.getSelector() != null) {
1375 throw new SecurityException(
1376 "Selector not allowed with ignoreTargetSecurity");
1377 }
1378 }
1379 targetUid = sourceRecord.launchedFromUid;
1380 targetPackage = sourceRecord.launchedFromPackage;
1381 isResolver = sourceRecord.isResolverOrChildActivity();
1382 }
1383
1384 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001385 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 }
1387
1388 // TODO: Switch to user app stacks here.
1389 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001390 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 .setCallingUid(targetUid)
1392 .setCallingPackage(targetPackage)
1393 .setResolvedType(resolvedType)
1394 .setResultTo(resultTo)
1395 .setResultWho(resultWho)
1396 .setRequestCode(requestCode)
1397 .setStartFlags(startFlags)
1398 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001399 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1401 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001402 // The target may well be in the background, which would normally prevent it
1403 // from starting an activity. Here we definitely want the start to succeed.
1404 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 .execute();
1406 } catch (SecurityException e) {
1407 // XXX need to figure out how to propagate to original app.
1408 // A SecurityException here is generally actually a fault of the original
1409 // calling activity (such as a fairly granting permissions), so propagate it
1410 // back to them.
1411 /*
1412 StringBuilder msg = new StringBuilder();
1413 msg.append("While launching");
1414 msg.append(intent.toString());
1415 msg.append(": ");
1416 msg.append(e.getMessage());
1417 */
1418 throw e;
1419 }
1420 }
1421
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001422 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1423 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1424 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1425 }
1426
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 @Override
1428 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1429 Intent intent, String resolvedType, IVoiceInteractionSession session,
1430 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1431 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 if (session == null || interactor == null) {
1434 throw new NullPointerException("null session or interactor");
1435 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001438 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 .setCallingUid(callingUid)
1440 .setCallingPackage(callingPackage)
1441 .setResolvedType(resolvedType)
1442 .setVoiceSession(session)
1443 .setVoiceInteractor(interactor)
1444 .setStartFlags(startFlags)
1445 .setProfilerInfo(profilerInfo)
1446 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001447 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001448 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 .execute();
1450 }
1451
1452 @Override
1453 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1454 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1456 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001458 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .setCallingUid(callingUid)
1460 .setCallingPackage(callingPackage)
1461 .setResolvedType(resolvedType)
1462 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001463 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001464 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .execute();
1466 }
1467
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 /**
1469 * Start the recents activity to perform the recents animation.
1470 *
1471 * @param intent The intent to start the recents activity.
1472 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1473 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001475 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1476 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001477 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 final long origId = Binder.clearCallingIdentity();
1481 try {
1482 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001483 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1484 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001485 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486
1487 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001488 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001489 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001490 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001491 if (recentsAnimationRunner == null) {
1492 anim.preloadRecentsActivity();
1493 } else {
1494 anim.startRecentsActivity(recentsAnimationRunner);
1495 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 }
1497 } finally {
1498 Binder.restoreCallingIdentity(origId);
1499 }
1500 }
1501
1502 @Override
1503 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001504 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 "startActivityFromRecents()");
1506
1507 final int callingPid = Binder.getCallingPid();
1508 final int callingUid = Binder.getCallingUid();
1509 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1510 final long origId = Binder.clearCallingIdentity();
1511 try {
1512 synchronized (mGlobalLock) {
1513 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1514 safeOptions);
1515 }
1516 } finally {
1517 Binder.restoreCallingIdentity(origId);
1518 }
1519 }
1520
1521 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001522 * Public API to check if the client is allowed to start an activity on specified display.
1523 *
1524 * If the target display is private or virtual, some restrictions will apply.
1525 *
1526 * @param displayId Target display id.
1527 * @param intent Intent used to launch the activity.
1528 * @param resolvedType The MIME type of the intent.
1529 * @param userId The id of the user for whom the call is made.
1530 * @return {@code true} if a call to start an activity on the target display should succeed and
1531 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1532 */
1533 @Override
1534 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1535 String resolvedType, int userId) {
1536 final int callingUid = Binder.getCallingUid();
1537 final int callingPid = Binder.getCallingPid();
1538 final long origId = Binder.clearCallingIdentity();
1539
1540 try {
1541 // Collect information about the target of the Intent.
1542 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1543 0 /* startFlags */, null /* profilerInfo */, userId,
1544 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1545 UserHandle.USER_NULL));
1546 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1547
1548 synchronized (mGlobalLock) {
1549 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1550 aInfo);
1551 }
1552 } finally {
1553 Binder.restoreCallingIdentity(origId);
1554 }
1555 }
1556
1557 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 * This is the internal entry point for handling Activity.finish().
1559 *
1560 * @param token The Binder token referencing the Activity we want to finish.
1561 * @param resultCode Result code, if any, from this Activity.
1562 * @param resultData Result data (Intent), if any, from this Activity.
1563 * @param finishTask Whether to finish the task associated with this Activity.
1564 *
1565 * @return Returns true if the activity successfully finished, or false if it is still running.
1566 */
1567 @Override
1568 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1569 int finishTask) {
1570 // Refuse possible leaked file descriptors
1571 if (resultData != null && resultData.hasFileDescriptors()) {
1572 throw new IllegalArgumentException("File descriptors passed in Intent");
1573 }
1574
1575 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (r == null) {
1578 return true;
1579 }
1580 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001581 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001582 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 if (rootR == null) {
1584 Slog.w(TAG, "Finishing task with all activities already finished");
1585 }
1586 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1587 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001588 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 return false;
1590 }
1591
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001592 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1593 // We should consolidate.
1594 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001596 final ActivityRecord next =
1597 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 if (next != null) {
1599 // ask watcher if this is allowed
1600 boolean resumeOK = true;
1601 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001602 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001604 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 Watchdog.getInstance().setActivityController(null);
1606 }
1607
1608 if (!resumeOK) {
1609 Slog.i(TAG, "Not finishing activity because controller resumed");
1610 return false;
1611 }
1612 }
1613 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001614
1615 // note down that the process has finished an activity and is in background activity
1616 // starts grace period
1617 if (r.app != null) {
1618 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1619 }
1620
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001622 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 try {
1624 boolean res;
1625 final boolean finishWithRootActivity =
1626 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1627 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1628 || (finishWithRootActivity && r == rootR)) {
1629 // If requested, remove the task that is associated to this activity only if it
1630 // was the root activity in the task. The result code and data is ignored
1631 // because we don't support returning them across task boundaries. Also, to
1632 // keep backwards compatibility we remove the task from recents when finishing
1633 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001634 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001636 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001637 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001638 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001640 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001641 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642 if (!res) {
1643 Slog.i(TAG, "Failed to finish by app-request");
1644 }
1645 }
1646 return res;
1647 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001648 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public boolean finishActivityAffinity(IBinder token) {
1656 synchronized (mGlobalLock) {
1657 final long origId = Binder.clearCallingIdentity();
1658 try {
1659 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1660 if (r == null) {
1661 return false;
1662 }
1663
1664 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1665 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001666 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 return false;
1668 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001669
1670 final PooledFunction p = PooledLambda.obtainFunction(
1671 ActivityRecord::finishIfSameAffinity, r,
1672 PooledLambda.__(ActivityRecord.class));
1673 r.getTask().forAllActivities(
1674 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1675 p.recycle();
1676
Andrii Kuliande93eff2019-07-12 12:21:27 -07001677 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 } finally {
1679 Binder.restoreCallingIdentity(origId);
1680 }
1681 }
1682 }
1683
1684 @Override
1685 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1686 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001687 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001688 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001689 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001690 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1691 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001692 return;
1693 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001694 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1695 false /* processPausingActivities */, config);
1696 if (stopProfiling && r.hasProcess()) {
1697 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 }
1699 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001700 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001701 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001702 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 }
1705
1706 @Override
1707 public final void activityResumed(IBinder token) {
1708 final long origId = Binder.clearCallingIdentity();
1709 synchronized (mGlobalLock) {
1710 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 }
1712 Binder.restoreCallingIdentity(origId);
1713 }
1714
1715 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001716 public final void activityTopResumedStateLost() {
1717 final long origId = Binder.clearCallingIdentity();
1718 synchronized (mGlobalLock) {
1719 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1720 }
1721 Binder.restoreCallingIdentity(origId);
1722 }
1723
1724 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001725 public final void activityPaused(IBinder token) {
1726 final long origId = Binder.clearCallingIdentity();
1727 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001728 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001729 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1730 if (r != null) {
1731 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001732 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001733 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 }
1735 Binder.restoreCallingIdentity(origId);
1736 }
1737
1738 @Override
1739 public final void activityStopped(IBinder token, Bundle icicle,
1740 PersistableBundle persistentState, CharSequence description) {
1741 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1742
1743 // Refuse possible leaked file descriptors
1744 if (icicle != null && icicle.hasFileDescriptors()) {
1745 throw new IllegalArgumentException("File descriptors passed in Bundle");
1746 }
1747
1748 final long origId = Binder.clearCallingIdentity();
1749
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001750 String restartingName = null;
1751 int restartingUid = 0;
1752 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001754 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001755 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001757 if (r.attachedToProcess()
1758 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1759 // The activity was requested to restart from
1760 // {@link #restartActivityProcessIfVisible}.
1761 restartingName = r.app.mName;
1762 restartingUid = r.app.mUid;
1763 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001764 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001765 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001766 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001767 }
1768
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001769 if (restartingName != null) {
1770 // In order to let the foreground activity can be restarted with its saved state from
1771 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1772 // until the activity reports stopped with the state. And the activity record will be
1773 // kept because the record state is restarting, then the activity will be restarted
1774 // immediately if it is still the top one.
1775 mStackSupervisor.removeRestartTimeouts(r);
1776 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1777 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001778 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779
1780 Binder.restoreCallingIdentity(origId);
1781 }
1782
1783 @Override
1784 public final void activityDestroyed(IBinder token) {
1785 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1786 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001787 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001788 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001789 try {
1790 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1791 if (activity != null) {
1792 activity.destroyed("activityDestroyed");
1793 }
1794 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001795 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001796 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001797 }
1798 }
1799 }
1800
1801 @Override
1802 public final void activityRelaunched(IBinder token) {
1803 final long origId = Binder.clearCallingIdentity();
1804 synchronized (mGlobalLock) {
1805 mStackSupervisor.activityRelaunchedLocked(token);
1806 }
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809
1810 public final void activitySlept(IBinder token) {
1811 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1812
1813 final long origId = Binder.clearCallingIdentity();
1814
1815 synchronized (mGlobalLock) {
1816 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1817 if (r != null) {
1818 mStackSupervisor.activitySleptLocked(r);
1819 }
1820 }
1821
1822 Binder.restoreCallingIdentity(origId);
1823 }
1824
1825 @Override
1826 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1827 synchronized (mGlobalLock) {
1828 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1829 if (r == null) {
1830 return;
1831 }
1832 final long origId = Binder.clearCallingIdentity();
1833 try {
1834 r.setRequestedOrientation(requestedOrientation);
1835 } finally {
1836 Binder.restoreCallingIdentity(origId);
1837 }
1838 }
1839 }
1840
1841 @Override
1842 public int getRequestedOrientation(IBinder token) {
1843 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001844 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1845 return (r != null)
1846 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001847 }
1848 }
1849
1850 @Override
1851 public void setImmersive(IBinder token, boolean immersive) {
1852 synchronized (mGlobalLock) {
1853 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1854 if (r == null) {
1855 throw new IllegalArgumentException();
1856 }
1857 r.immersive = immersive;
1858
1859 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001860 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 }
1864 }
1865 }
1866
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001867 void applyUpdateLockStateLocked(ActivityRecord r) {
1868 // Modifications to the UpdateLock state are done on our handler, outside
1869 // the activity manager's locks. The new state is determined based on the
1870 // state *now* of the relevant activity record. The object is passed to
1871 // the handler solely for logging detail, not to be consulted/modified.
1872 final boolean nextState = r != null && r.immersive;
1873 mH.post(() -> {
1874 if (mUpdateLock.isHeld() != nextState) {
1875 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1876 "Applying new update lock state '" + nextState + "' for " + r);
1877 if (nextState) {
1878 mUpdateLock.acquire();
1879 } else {
1880 mUpdateLock.release();
1881 }
1882 }
1883 });
1884 }
1885
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 @Override
1887 public boolean isImmersive(IBinder token) {
1888 synchronized (mGlobalLock) {
1889 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1890 if (r == null) {
1891 throw new IllegalArgumentException();
1892 }
1893 return r.immersive;
1894 }
1895 }
1896
1897 @Override
1898 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001899 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001901 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 return (r != null) ? r.immersive : false;
1903 }
1904 }
1905
1906 @Override
1907 public void overridePendingTransition(IBinder token, String packageName,
1908 int enterAnim, int exitAnim) {
1909 synchronized (mGlobalLock) {
1910 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1911 if (self == null) {
1912 return;
1913 }
1914
1915 final long origId = Binder.clearCallingIdentity();
1916
1917 if (self.isState(
1918 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001919 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001920 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 }
1922
1923 Binder.restoreCallingIdentity(origId);
1924 }
1925 }
1926
1927 @Override
1928 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001929 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001930 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001931 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 if (r == null) {
1933 return ActivityManager.COMPAT_MODE_UNKNOWN;
1934 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001935 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001936 }
1937 }
1938
1939 @Override
1940 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001941 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001943 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001945 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 if (r == null) {
1947 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1948 return;
1949 }
1950 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001951 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 }
1953 }
1954
1955 @Override
1956 public int getLaunchedFromUid(IBinder activityToken) {
1957 ActivityRecord srec;
1958 synchronized (mGlobalLock) {
1959 srec = ActivityRecord.forTokenLocked(activityToken);
1960 }
1961 if (srec == null) {
1962 return -1;
1963 }
1964 return srec.launchedFromUid;
1965 }
1966
1967 @Override
1968 public String getLaunchedFromPackage(IBinder activityToken) {
1969 ActivityRecord srec;
1970 synchronized (mGlobalLock) {
1971 srec = ActivityRecord.forTokenLocked(activityToken);
1972 }
1973 if (srec == null) {
1974 return null;
1975 }
1976 return srec.launchedFromPackage;
1977 }
1978
1979 @Override
1980 public boolean convertFromTranslucent(IBinder token) {
1981 final long origId = Binder.clearCallingIdentity();
1982 try {
1983 synchronized (mGlobalLock) {
1984 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1985 if (r == null) {
1986 return false;
1987 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001988 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 }
1990 } finally {
1991 Binder.restoreCallingIdentity(origId);
1992 }
1993 }
1994
1995 @Override
1996 public boolean convertToTranslucent(IBinder token, Bundle options) {
1997 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1998 final long origId = Binder.clearCallingIdentity();
1999 try {
2000 synchronized (mGlobalLock) {
2001 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2002 if (r == null) {
2003 return false;
2004 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002005 final ActivityRecord under = r.getTask().getActivityBelow(r);
2006 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2008 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002009 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 }
2011 } finally {
2012 Binder.restoreCallingIdentity(origId);
2013 }
2014 }
2015
2016 @Override
2017 public void notifyActivityDrawn(IBinder token) {
2018 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2019 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002020 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002022 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 }
2024 }
2025 }
2026
2027 @Override
2028 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2029 synchronized (mGlobalLock) {
2030 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2031 if (r == null) {
2032 return;
2033 }
2034 r.reportFullyDrawnLocked(restoredFromBundle);
2035 }
2036 }
2037
2038 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002039 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 synchronized (mGlobalLock) {
2041 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08002042 if (stack != null && stack.getDisplayId() != INVALID_DISPLAY) {
2043 return stack.getDisplayId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 }
2045 return DEFAULT_DISPLAY;
2046 }
2047 }
2048
2049 @Override
2050 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002051 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 long ident = Binder.clearCallingIdentity();
2053 try {
2054 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002055 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 if (focusedStack != null) {
Louis Chang149d5c82019-12-30 09:47:39 +08002057 return mRootWindowContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 }
2059 return null;
2060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(ident);
2063 }
2064 }
2065
2066 @Override
2067 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002068 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2070 final long callingId = Binder.clearCallingIdentity();
2071 try {
2072 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002073 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 if (stack == null) {
2075 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2076 return;
2077 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002078 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002079 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002080 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 }
2082 }
2083 } finally {
2084 Binder.restoreCallingIdentity(callingId);
2085 }
2086 }
2087
2088 @Override
2089 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002090 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2092 final long callingId = Binder.clearCallingIdentity();
2093 try {
2094 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002095 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002096 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 if (task == null) {
2098 return;
2099 }
2100 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002101 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002102 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 }
2104 }
2105 } finally {
2106 Binder.restoreCallingIdentity(callingId);
2107 }
2108 }
2109
2110 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002111 public void restartActivityProcessIfVisible(IBinder activityToken) {
2112 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2113 final long callingId = Binder.clearCallingIdentity();
2114 try {
2115 synchronized (mGlobalLock) {
2116 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2117 if (r == null) {
2118 return;
2119 }
2120 r.restartProcessIfVisible();
2121 }
2122 } finally {
2123 Binder.restoreCallingIdentity(callingId);
2124 }
2125 }
2126
2127 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002129 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 synchronized (mGlobalLock) {
2131 final long ident = Binder.clearCallingIdentity();
2132 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002133 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 "remove-task");
2135 } finally {
2136 Binder.restoreCallingIdentity(ident);
2137 }
2138 }
2139 }
2140
2141 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002142 public void removeAllVisibleRecentTasks() {
2143 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2144 synchronized (mGlobalLock) {
2145 final long ident = Binder.clearCallingIdentity();
2146 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002147 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002148 } finally {
2149 Binder.restoreCallingIdentity(ident);
2150 }
2151 }
2152 }
2153
2154 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2156 synchronized (mGlobalLock) {
2157 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2158 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002159 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002160 }
2161 }
2162 return false;
2163 }
2164
2165 @Override
2166 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2167 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002168
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002169 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002170 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2171 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002172 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002173 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002174 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002175 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 }
2177 }
2178
2179 /**
2180 * Attempts to move a task backwards in z-order (the order of activities within the task is
2181 * unchanged).
2182 *
2183 * There are several possible results of this call:
2184 * - if the task is locked, then we will show the lock toast
2185 * - if there is a task behind the provided task, then that task is made visible and resumed as
2186 * this task is moved to the back
2187 * - otherwise, if there are no other tasks in the stack:
2188 * - if this task is in the pinned stack, then we remove the stack completely, which will
2189 * have the effect of moving the task to the top or bottom of the fullscreen stack
2190 * (depending on whether it is visible)
2191 * - otherwise, we simply return home and hide this task
2192 *
2193 * @param token A reference to the activity we wish to move
2194 * @param nonRoot If false then this only works if the activity is the root
2195 * of a task; if true it will work for any activity in a task.
2196 * @return Returns true if the move completed, false if not.
2197 */
2198 @Override
2199 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 synchronized (mGlobalLock) {
2202 final long origId = Binder.clearCallingIdentity();
2203 try {
2204 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002205 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002207 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208 }
2209 } finally {
2210 Binder.restoreCallingIdentity(origId);
2211 }
2212 }
2213 return false;
2214 }
2215
2216 @Override
2217 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002218 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002219 long ident = Binder.clearCallingIdentity();
2220 Rect rect = new Rect();
2221 try {
2222 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002223 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2225 if (task == null) {
2226 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2227 return rect;
2228 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002229 if (task.getParent() != null) {
2230 rect.set(task.getBounds());
2231 } else if (task.mLastNonFullscreenBounds != null) {
2232 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 }
2234 }
2235 } finally {
2236 Binder.restoreCallingIdentity(ident);
2237 }
2238 return rect;
2239 }
2240
2241 @Override
2242 public ActivityManager.TaskDescription getTaskDescription(int id) {
2243 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002244 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002246 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2248 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002249 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 }
2251 }
2252 return null;
2253 }
2254
2255 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002256 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2257 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2258 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2259 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2260 return;
2261 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002262 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002263 synchronized (mGlobalLock) {
2264 final long ident = Binder.clearCallingIdentity();
2265 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002266 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002267 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002268 if (task == null) {
2269 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2270 return;
2271 }
2272
2273 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2274 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2275
2276 if (!task.isActivityTypeStandardOrUndefined()) {
2277 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2278 + " non-standard task " + taskId + " to windowing mode="
2279 + windowingMode);
2280 }
2281
2282 final ActivityStack stack = task.getStack();
2283 if (toTop) {
2284 stack.moveToFront("setTaskWindowingMode", task);
2285 }
2286 stack.setWindowingMode(windowingMode);
2287 } finally {
2288 Binder.restoreCallingIdentity(ident);
2289 }
2290 }
2291 }
2292
2293 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002295 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002296 ActivityRecord r = getCallingRecordLocked(token);
2297 return r != null ? r.info.packageName : null;
2298 }
2299 }
2300
2301 @Override
2302 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002303 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 ActivityRecord r = getCallingRecordLocked(token);
2305 return r != null ? r.intent.getComponent() : null;
2306 }
2307 }
2308
2309 private ActivityRecord getCallingRecordLocked(IBinder token) {
2310 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2311 if (r == null) {
2312 return null;
2313 }
2314 return r.resultTo;
2315 }
2316
2317 @Override
2318 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002319 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002320
2321 synchronized (mGlobalLock) {
2322 final long origId = Binder.clearCallingIdentity();
2323 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002324 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002325 } finally {
2326 Binder.restoreCallingIdentity(origId);
2327 }
2328 }
2329 }
2330
Mark Renouf446251d2019-04-26 10:22:41 -04002331 @Override
2332 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2333 synchronized (mGlobalLock) {
2334 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2335 if (r == null) {
2336 return;
2337 }
2338 ActivityStack stack = r.getActivityStack();
2339 if (stack != null && stack.isSingleTaskInstance()) {
2340 // Single-task stacks are used for activities which are presented in floating
2341 // windows above full screen activities. Instead of directly finishing the
2342 // task, a task change listener is used to notify SystemUI so the action can be
2343 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002344 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002345 mTaskChangeNotificationController
2346 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2347 } else {
2348 try {
2349 callback.requestFinish();
2350 } catch (RemoteException e) {
2351 Slog.e(TAG, "Failed to invoke request finish callback", e);
2352 }
2353 }
2354 }
2355 }
2356
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002357 /**
2358 * TODO: Add mController hook
2359 */
2360 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002361 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2362 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002363 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364
2365 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2366 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002367 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2368 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 }
2370 }
2371
Ricky Waiaca8a772019-04-04 16:01:06 +01002372 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2373 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002374 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002375
Ricky Waiaca8a772019-04-04 16:01:06 +01002376 final int callingPid = Binder.getCallingPid();
2377 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002378 if (!isSameApp(callingUid, callingPackage)) {
2379 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2380 + Binder.getCallingPid() + " as package " + callingPackage;
2381 Slog.w(TAG, msg);
2382 throw new SecurityException(msg);
2383 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002384 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 SafeActivityOptions.abort(options);
2386 return;
2387 }
2388 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002389 WindowProcessController callerApp = null;
2390 if (appThread != null) {
2391 callerApp = getProcessController(appThread);
2392 }
2393 final ActivityStarter starter = getActivityStartController().obtainStarter(
2394 null /* intent */, "moveTaskToFront");
2395 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2396 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002397 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002398 return;
2399 }
2400 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002401 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002402 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002403 if (task == null) {
2404 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002405 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 return;
2407 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002408 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002410 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 return;
2412 }
2413 ActivityOptions realOptions = options != null
2414 ? options.getOptions(mStackSupervisor)
2415 : null;
2416 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2417 false /* forceNonResizable */);
2418
Wale Ogunwale21e06482019-11-18 05:14:15 -08002419 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 if (topActivity != null) {
2421
2422 // We are reshowing a task, use a starting window to hide the initial draw delay
2423 // so the transition can start earlier.
2424 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2425 true /* taskSwitch */, fromRecents);
2426 }
2427 } finally {
2428 Binder.restoreCallingIdentity(origId);
2429 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 }
2431
Ricky Waiaca8a772019-04-04 16:01:06 +01002432 /**
2433 * Return true if callingUid is system, or packageName belongs to that callingUid.
2434 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002435 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002436 try {
2437 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2438 if (packageName == null) {
2439 return false;
2440 }
2441 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2442 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2443 UserHandle.getUserId(callingUid));
2444 return UserHandle.isSameApp(callingUid, uid);
2445 }
2446 } catch (RemoteException e) {
2447 // Should not happen
2448 }
2449 return true;
2450 }
2451
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002452 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2453 int callingPid, int callingUid, String name) {
2454 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2455 return true;
2456 }
2457
2458 if (getRecentTasks().isCallerRecents(sourceUid)) {
2459 return true;
2460 }
2461
2462 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2463 if (perm == PackageManager.PERMISSION_GRANTED) {
2464 return true;
2465 }
2466 if (checkAllowAppSwitchUid(sourceUid)) {
2467 return true;
2468 }
2469
2470 // If the actual IPC caller is different from the logical source, then
2471 // also see if they are allowed to control app switches.
2472 if (callingUid != -1 && callingUid != sourceUid) {
2473 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2474 if (perm == PackageManager.PERMISSION_GRANTED) {
2475 return true;
2476 }
2477 if (checkAllowAppSwitchUid(callingUid)) {
2478 return true;
2479 }
2480 }
2481
2482 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2483 return false;
2484 }
2485
2486 private boolean checkAllowAppSwitchUid(int uid) {
2487 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2488 if (types != null) {
2489 for (int i = types.size() - 1; i >= 0; i--) {
2490 if (types.valueAt(i).intValue() == uid) {
2491 return true;
2492 }
2493 }
2494 }
2495 return false;
2496 }
2497
2498 @Override
2499 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2500 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2501 "setActivityController()");
2502 synchronized (mGlobalLock) {
2503 mController = controller;
2504 mControllerIsAMonkey = imAMonkey;
2505 Watchdog.getInstance().setActivityController(controller);
2506 }
2507 }
2508
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002509 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002510 synchronized (mGlobalLock) {
2511 return mController != null && mControllerIsAMonkey;
2512 }
2513 }
2514
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002515 @Override
2516 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2517 synchronized (mGlobalLock) {
2518 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2519 }
2520 }
2521
2522 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002523 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2524 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2525 }
2526
2527 @Override
2528 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2529 @WindowConfiguration.ActivityType int ignoreActivityType,
2530 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2531 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002532 final int callingPid = Binder.getCallingPid();
2533 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002534 final int[] profileIds = getUserManager().getProfileIds(
2535 UserHandle.getUserId(callingUid), true);
2536 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2537 for (int i = 0; i < profileIds.length; i++) {
2538 callingProfileIds.add(profileIds[i]);
2539 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002540 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2541
2542 synchronized (mGlobalLock) {
2543 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2544
Nicholas Sauer0259e532019-08-30 08:24:55 -07002545 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002546 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002547 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002548 }
2549
2550 return list;
2551 }
2552
2553 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2555 synchronized (mGlobalLock) {
2556 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002557 try {
2558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2559 if (r == null) return;
2560
2561 final PooledConsumer c = PooledLambda.obtainConsumer(
2562 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2563 r, resultWho, requestCode);
2564 // TODO: This should probably only loop over the task since you need to be in the
2565 // same task to return results.
2566 r.getActivityStack().forAllActivities(c);
2567 c.recycle();
2568
2569 updateOomAdj();
2570 } finally {
2571 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002572 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002573 }
2574 }
2575
2576 @Override
2577 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002578 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002579 ActivityStack stack = ActivityRecord.getStackLocked(token);
2580 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002581 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002582 }
2583 return false;
2584 }
2585 }
2586
2587 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002589 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590 synchronized (mGlobalLock) {
2591 final long ident = Binder.clearCallingIdentity();
2592 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002593 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 if (task == null) {
2595 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2596 return;
2597 }
2598
2599 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2600 + " to stackId=" + stackId + " toTop=" + toTop);
2601
Louis Chang149d5c82019-12-30 09:47:39 +08002602 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002603 if (stack == null) {
2604 throw new IllegalStateException(
2605 "moveTaskToStack: No stack for stackId=" + stackId);
2606 }
2607 if (!stack.isActivityTypeStandardOrUndefined()) {
2608 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2609 + taskId + " to stack " + stackId);
2610 }
2611 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002612 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2614 }
2615 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2616 "moveTaskToStack");
2617 } finally {
2618 Binder.restoreCallingIdentity(ident);
2619 }
2620 }
2621 }
2622
2623 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002624 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2625 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002626
2627 final long ident = Binder.clearCallingIdentity();
2628 try {
2629 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002630 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002631 if (stack == null) {
2632 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2633 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002634 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002635 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2636 throw new IllegalArgumentException("Stack: " + stackId
2637 + " doesn't support animated resize.");
2638 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002639 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002640 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002641 }
2642 } finally {
2643 Binder.restoreCallingIdentity(ident);
2644 }
2645 }
2646
wilsonshih5c4cf522019-01-25 09:03:47 +08002647 @Override
2648 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2649 int animationDuration) {
2650 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2651
2652 final long ident = Binder.clearCallingIdentity();
2653 try {
2654 synchronized (mGlobalLock) {
2655 if (xOffset == 0 && yOffset == 0) {
2656 return;
2657 }
Louis Chang149d5c82019-12-30 09:47:39 +08002658 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002659 if (stack == null) {
2660 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2661 return;
2662 }
2663 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2664 throw new IllegalArgumentException("Stack: " + stackId
2665 + " doesn't support animated resize.");
2666 }
2667 final Rect destBounds = new Rect();
2668 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002669 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002670 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2671 return;
2672 }
2673 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002674 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002675 animationDuration, false /* fromFullscreen */);
2676 }
2677 } finally {
2678 Binder.restoreCallingIdentity(ident);
2679 }
2680 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002681 /**
2682 * Moves the specified task to the primary-split-screen stack.
2683 *
2684 * @param taskId Id of task to move.
2685 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2686 * exist already. See
2687 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2688 * and
2689 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2690 * @param toTop If the task and stack should be moved to the top.
2691 * @param animate Whether we should play an animation for the moving the task.
2692 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2693 * stack. Pass {@code null} to use default bounds.
2694 * @param showRecents If the recents activity should be shown on the other side of the task
2695 * going into split-screen mode.
2696 */
2697 @Override
2698 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2699 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002700 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 "setTaskWindowingModeSplitScreenPrimary()");
2702 synchronized (mGlobalLock) {
2703 final long ident = Binder.clearCallingIdentity();
2704 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002705 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002706 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002707 if (task == null) {
2708 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2709 return false;
2710 }
2711 if (DEBUG_STACK) Slog.d(TAG_STACK,
2712 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2713 + " to createMode=" + createMode + " toTop=" + toTop);
2714 if (!task.isActivityTypeStandardOrUndefined()) {
2715 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2716 + " non-standard task " + taskId + " to split-screen windowing mode");
2717 }
2718
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002719 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 final int windowingMode = task.getWindowingMode();
2721 final ActivityStack stack = task.getStack();
2722 if (toTop) {
2723 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2724 }
2725 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002726 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2727 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002728 return windowingMode != task.getWindowingMode();
2729 } finally {
2730 Binder.restoreCallingIdentity(ident);
2731 }
2732 }
2733 }
2734
2735 /**
2736 * Removes stacks in the input windowing modes from the system if they are of activity type
2737 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2738 */
2739 @Override
2740 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002741 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002742 "removeStacksInWindowingModes()");
2743
2744 synchronized (mGlobalLock) {
2745 final long ident = Binder.clearCallingIdentity();
2746 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002747 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002748 } finally {
2749 Binder.restoreCallingIdentity(ident);
2750 }
2751 }
2752 }
2753
2754 @Override
2755 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002757 "removeStacksWithActivityTypes()");
2758
2759 synchronized (mGlobalLock) {
2760 final long ident = Binder.clearCallingIdentity();
2761 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002762 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002763 } finally {
2764 Binder.restoreCallingIdentity(ident);
2765 }
2766 }
2767 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768
2769 @Override
2770 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2771 int userId) {
2772 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2774 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 final boolean detailed = checkGetTasksPermission(
2777 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2778 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 == PackageManager.PERMISSION_GRANTED;
2780
2781 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002782 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 callingUid);
2784 }
2785 }
2786
2787 @Override
2788 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002789 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 long ident = Binder.clearCallingIdentity();
2791 try {
2792 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002793 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 }
2795 } finally {
2796 Binder.restoreCallingIdentity(ident);
2797 }
2798 }
2799
2800 @Override
2801 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002802 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002803 long ident = Binder.clearCallingIdentity();
2804 try {
2805 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002806 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002807 }
2808 } finally {
2809 Binder.restoreCallingIdentity(ident);
2810 }
2811 }
2812
2813 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002814 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2815 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2816 long ident = Binder.clearCallingIdentity();
2817 try {
2818 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002819 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002820 }
2821 } finally {
2822 Binder.restoreCallingIdentity(ident);
2823 }
2824 }
2825
2826 @Override
2827 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2828 int displayId) {
2829 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2830 long ident = Binder.clearCallingIdentity();
2831 try {
2832 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002833 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002834 }
2835 } finally {
2836 Binder.restoreCallingIdentity(ident);
2837 }
2838 }
2839
2840 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002841 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002842 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 final long callingUid = Binder.getCallingUid();
2844 final long origId = Binder.clearCallingIdentity();
2845 try {
2846 synchronized (mGlobalLock) {
2847 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002848 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2850 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2851 }
2852 } finally {
2853 Binder.restoreCallingIdentity(origId);
2854 }
2855 }
2856
2857 @Override
2858 public void startLockTaskModeByToken(IBinder token) {
2859 synchronized (mGlobalLock) {
2860 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2861 if (r == null) {
2862 return;
2863 }
Louis Changcdec0802019-11-11 11:45:07 +08002864 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865 }
2866 }
2867
2868 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002869 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002870 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002871 // This makes inner call to look as if it was initiated by system.
2872 long ident = Binder.clearCallingIdentity();
2873 try {
2874 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002875 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002876 MATCH_TASK_IN_STACKS_ONLY);
2877 if (task == null) {
2878 return;
2879 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880
2881 // When starting lock task mode the stack must be in front and focused
2882 task.getStack().moveToFront("startSystemLockTaskMode");
2883 startLockTaskModeLocked(task, true /* isSystemCaller */);
2884 }
2885 } finally {
2886 Binder.restoreCallingIdentity(ident);
2887 }
2888 }
2889
2890 @Override
2891 public void stopLockTaskModeByToken(IBinder token) {
2892 synchronized (mGlobalLock) {
2893 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2894 if (r == null) {
2895 return;
2896 }
Louis Changcdec0802019-11-11 11:45:07 +08002897 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 }
2899 }
2900
2901 /**
2902 * This API should be called by SystemUI only when user perform certain action to dismiss
2903 * lock task mode. We should only dismiss pinned lock task mode in this case.
2904 */
2905 @Override
2906 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002907 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002908 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2909 }
2910
Louis Changcdec0802019-11-11 11:45:07 +08002911 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2913 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2914 return;
2915 }
2916
Louis Chang149d5c82019-12-30 09:47:39 +08002917 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002918 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 throw new IllegalArgumentException("Invalid task, not in foreground");
2920 }
2921
2922 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2923 // system or a specific app.
2924 // * System-initiated requests will only start the pinned mode (screen pinning)
2925 // * App-initiated requests
2926 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2927 // - will start the pinned mode, otherwise
2928 final int callingUid = Binder.getCallingUid();
2929 long ident = Binder.clearCallingIdentity();
2930 try {
2931 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002932 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002933
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002934 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 } finally {
2936 Binder.restoreCallingIdentity(ident);
2937 }
2938 }
2939
Louis Changcdec0802019-11-11 11:45:07 +08002940 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 final int callingUid = Binder.getCallingUid();
2942 long ident = Binder.clearCallingIdentity();
2943 try {
2944 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002945 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2948 // task and jumping straight into a call in the case of emergency call back.
2949 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2950 if (tm != null) {
2951 tm.showInCallScreen(false);
2952 }
2953 } finally {
2954 Binder.restoreCallingIdentity(ident);
2955 }
2956 }
2957
2958 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002959 public void updateLockTaskPackages(int userId, String[] packages) {
2960 final int callingUid = Binder.getCallingUid();
2961 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2962 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2963 "updateLockTaskPackages()");
2964 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002965 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002966 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2967 + Arrays.toString(packages));
2968 getLockTaskController().updateLockTaskPackages(userId, packages);
2969 }
2970 }
2971
2972 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 public boolean isInLockTaskMode() {
2974 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2975 }
2976
2977 @Override
2978 public int getLockTaskModeState() {
2979 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002980 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002981 }
2982 }
2983
2984 @Override
2985 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2986 synchronized (mGlobalLock) {
2987 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2988 if (r != null) {
2989 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002990 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002991 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994 }
2995
2996 @Override
2997 public Bundle getActivityOptions(IBinder token) {
2998 final long origId = Binder.clearCallingIdentity();
2999 try {
3000 synchronized (mGlobalLock) {
3001 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3002 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003003 final ActivityOptions activityOptions = r.takeOptionsLocked(
3004 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 return activityOptions == null ? null : activityOptions.toBundle();
3006 }
3007 return null;
3008 }
3009 } finally {
3010 Binder.restoreCallingIdentity(origId);
3011 }
3012 }
3013
3014 @Override
3015 public List<IBinder> getAppTasks(String callingPackage) {
3016 int callingUid = Binder.getCallingUid();
3017 long ident = Binder.clearCallingIdentity();
3018 try {
3019 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003020 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 }
3022 } finally {
3023 Binder.restoreCallingIdentity(ident);
3024 }
3025 }
3026
3027 @Override
3028 public void finishVoiceTask(IVoiceInteractionSession session) {
3029 synchronized (mGlobalLock) {
3030 final long origId = Binder.clearCallingIdentity();
3031 try {
3032 // TODO: VI Consider treating local voice interactions and voice tasks
3033 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003034 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003035 } finally {
3036 Binder.restoreCallingIdentity(origId);
3037 }
3038 }
3039
3040 }
3041
3042 @Override
3043 public boolean isTopOfTask(IBinder token) {
3044 synchronized (mGlobalLock) {
3045 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003046 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 }
3048 }
3049
3050 @Override
3051 public void notifyLaunchTaskBehindComplete(IBinder token) {
3052 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3053 }
3054
3055 @Override
3056 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003057 mH.post(() -> {
3058 synchronized (mGlobalLock) {
3059 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003060 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003061 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003062 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003063 } catch (RemoteException e) {
3064 }
3065 }
3066 }
3067
3068 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 }
3070
3071 /** Called from an app when assist data is ready. */
3072 @Override
3073 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3074 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003075 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 synchronized (pae) {
3077 pae.result = extras;
3078 pae.structure = structure;
3079 pae.content = content;
3080 if (referrer != null) {
3081 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3082 }
3083 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003084 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003085 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003086 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087 structure.setHomeActivity(pae.isHome);
3088 }
3089 pae.haveResult = true;
3090 pae.notifyAll();
3091 if (pae.intent == null && pae.receiver == null) {
3092 // Caller is just waiting for the result.
3093 return;
3094 }
3095 }
3096 // We are now ready to launch the assist activity.
3097 IAssistDataReceiver sendReceiver = null;
3098 Bundle sendBundle = null;
3099 synchronized (mGlobalLock) {
3100 buildAssistBundleLocked(pae, extras);
3101 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003102 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 if (!exists) {
3104 // Timed out.
3105 return;
3106 }
3107
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003108 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 // Caller wants result sent back to them.
3110 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003111 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003112 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003113 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3114 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3116 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3117 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3118 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3119 }
3120 }
3121 if (sendReceiver != null) {
3122 try {
3123 sendReceiver.onHandleAssistData(sendBundle);
3124 } catch (RemoteException e) {
3125 }
3126 return;
3127 }
3128
3129 final long ident = Binder.clearCallingIdentity();
3130 try {
3131 if (TextUtils.equals(pae.intent.getAction(),
3132 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003133 // Start voice interaction through VoiceInteractionManagerService.
3134 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3135 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003136 } else {
3137 pae.intent.replaceExtras(pae.extras);
3138 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3139 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3140 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003141 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142
3143 try {
3144 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3145 } catch (ActivityNotFoundException e) {
3146 Slog.w(TAG, "No activity to handle assist action.", e);
3147 }
3148 }
3149 } finally {
3150 Binder.restoreCallingIdentity(ident);
3151 }
3152 }
3153
3154 @Override
3155 public int addAppTask(IBinder activityToken, Intent intent,
3156 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3157 final int callingUid = Binder.getCallingUid();
3158 final long callingIdent = Binder.clearCallingIdentity();
3159
3160 try {
3161 synchronized (mGlobalLock) {
3162 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3163 if (r == null) {
3164 throw new IllegalArgumentException("Activity does not exist; token="
3165 + activityToken);
3166 }
3167 ComponentName comp = intent.getComponent();
3168 if (comp == null) {
3169 throw new IllegalArgumentException("Intent " + intent
3170 + " must specify explicit component");
3171 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003172 if (thumbnail.getWidth() != mThumbnailWidth
3173 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003174 throw new IllegalArgumentException("Bad thumbnail size: got "
3175 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003176 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 }
3178 if (intent.getSelector() != null) {
3179 intent.setSelector(null);
3180 }
3181 if (intent.getSourceBounds() != null) {
3182 intent.setSourceBounds(null);
3183 }
3184 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3185 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3186 // The caller has added this as an auto-remove task... that makes no
3187 // sense, so turn off auto-remove.
3188 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3189 }
3190 }
3191 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3192 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3193 if (ainfo.applicationInfo.uid != callingUid) {
3194 throw new SecurityException(
3195 "Can't add task for another application: target uid="
3196 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3197 }
3198
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003199 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003200 final Task task = stack.createTask(
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08003201 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003202 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003203 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003205 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 return INVALID_TASK_ID;
3207 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003208 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209
3210 // TODO: Send the thumbnail to WM to store it.
3211
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003212 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213 }
3214 } finally {
3215 Binder.restoreCallingIdentity(callingIdent);
3216 }
3217 }
3218
3219 @Override
3220 public Point getAppTaskThumbnailSize() {
3221 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003222 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003223 }
3224 }
3225
3226 @Override
3227 public void setTaskResizeable(int taskId, int resizeableMode) {
3228 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003229 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003230 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3231 if (task == null) {
3232 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3233 return;
3234 }
3235 task.setResizeMode(resizeableMode);
3236 }
3237 }
3238
3239 @Override
3240 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 long ident = Binder.clearCallingIdentity();
3243 try {
3244 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003245 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003246 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003247 if (task == null) {
3248 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3249 return;
3250 }
3251 // Place the task in the right stack if it isn't there already based on
3252 // the requested bounds.
3253 // The stack transition logic is:
3254 // - a null bounds on a freeform task moves that task to fullscreen
3255 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3256 // that task to freeform
3257 // - otherwise the task is not moved
3258 ActivityStack stack = task.getStack();
3259 if (!task.getWindowConfiguration().canResizeTask()) {
3260 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3261 }
3262 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3263 stack = stack.getDisplay().getOrCreateStack(
3264 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3265 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3266 stack = stack.getDisplay().getOrCreateStack(
3267 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3268 }
3269
3270 // Reparent the task to the right stack if necessary
3271 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3272 if (stack != task.getStack()) {
3273 // Defer resume until the task is resized below
3274 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3275 DEFER_RESUME, "resizeTask");
3276 preserveWindow = false;
3277 }
3278
3279 // After reparenting (which only resizes the task to the stack bounds), resize the
3280 // task to the actual bounds provided
3281 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3282 }
3283 } finally {
3284 Binder.restoreCallingIdentity(ident);
3285 }
3286 }
3287
Evan Roskyddedfd42019-10-04 13:38:38 -07003288 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3289 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003290 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003291 throw new RuntimeException("Invalid token in task transaction");
3292 }
3293 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3294 // masks here.
3295 int configMask = change.getConfigSetMask();
3296 int windowMask = change.getWindowSetMask();
3297 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3298 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3299 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3300 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3301 c.setTo(change.getConfiguration(), configMask, windowMask);
3302 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003303 // TODO(b/145675353): remove the following once we could apply new bounds to the
3304 // pinned stack together with its children.
3305 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3306 }
3307
3308 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3309 int windowMask, Configuration config) {
3310 if ((container instanceof ActivityStack)
3311 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3312 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3313 final ActivityStack stack = (ActivityStack) container;
3314 if (stack.inPinnedWindowingMode()) {
3315 stack.resize(config.windowConfiguration.getBounds(),
3316 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3317 PRESERVE_WINDOWS, true /* deferResume */);
3318 }
3319 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003320 }
3321
3322 @Override
3323 public void applyContainerTransaction(WindowContainerTransaction t) {
3324 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3325 long ident = Binder.clearCallingIdentity();
3326 try {
3327 if (t == null) {
3328 return;
3329 }
3330 synchronized (mGlobalLock) {
3331 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3332 t.getChanges().entrySet().iterator();
3333 while (entries.hasNext()) {
3334 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3335 entries.next();
3336 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3337 entry.getKey()).getContainer();
3338 sanitizeAndApplyConfigChange(cc, entry.getValue());
3339 }
3340 }
3341 } finally {
3342 Binder.restoreCallingIdentity(ident);
3343 }
3344 }
3345
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 @Override
3347 public boolean releaseActivityInstance(IBinder token) {
3348 synchronized (mGlobalLock) {
3349 final long origId = Binder.clearCallingIdentity();
3350 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003351 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3352 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003353 return false;
3354 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003355 r.destroyImmediately(true /* removeFromApp */, "app-req");
3356 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 } finally {
3358 Binder.restoreCallingIdentity(origId);
3359 }
3360 }
3361 }
3362
3363 @Override
3364 public void releaseSomeActivities(IApplicationThread appInt) {
3365 synchronized (mGlobalLock) {
3366 final long origId = Binder.clearCallingIdentity();
3367 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003368 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003369 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 } finally {
3371 Binder.restoreCallingIdentity(origId);
3372 }
3373 }
3374 }
3375
3376 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003377 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003378 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 != PackageManager.PERMISSION_GRANTED) {
3380 throw new SecurityException("Requires permission "
3381 + android.Manifest.permission.DEVICE_POWER);
3382 }
3383
3384 synchronized (mGlobalLock) {
3385 long ident = Binder.clearCallingIdentity();
3386 if (mKeyguardShown != keyguardShowing) {
3387 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003388 final Message msg = PooledLambda.obtainMessage(
3389 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3390 keyguardShowing);
3391 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003392 }
3393 try {
wilsonshih177261f2019-02-22 12:02:18 +08003394 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 } finally {
3396 Binder.restoreCallingIdentity(ident);
3397 }
3398 }
3399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 mH.post(() -> {
3401 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3402 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3403 }
3404 });
3405 }
3406
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003407 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003408 mH.post(() -> {
3409 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3410 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3411 }
3412 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 }
3414
3415 @Override
3416 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003417 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3418 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419
3420 final File passedIconFile = new File(filePath);
3421 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3422 passedIconFile.getName());
3423 if (!legitIconFile.getPath().equals(filePath)
3424 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3425 throw new IllegalArgumentException("Bad file path: " + filePath
3426 + " passed for userId " + userId);
3427 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003428 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 }
3430
3431 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003433 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 synchronized (mGlobalLock) {
3435 final long ident = Binder.clearCallingIdentity();
3436 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003437 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 if (stack == null) {
3439 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3440 return;
3441 }
3442 if (!stack.isActivityTypeStandardOrUndefined()) {
3443 throw new IllegalArgumentException(
3444 "Removing non-standard stack is not allowed.");
3445 }
3446 mStackSupervisor.removeStack(stack);
3447 } finally {
3448 Binder.restoreCallingIdentity(ident);
3449 }
3450 }
3451 }
3452
3453 @Override
3454 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003455 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456
3457 synchronized (mGlobalLock) {
3458 final long ident = Binder.clearCallingIdentity();
3459 try {
3460 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3461 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003462 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003463 } finally {
3464 Binder.restoreCallingIdentity(ident);
3465 }
3466 }
3467 }
3468
3469 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003470 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003471 synchronized (mGlobalLock) {
3472 long ident = Binder.clearCallingIdentity();
3473 try {
3474 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3475 if (r == null) {
3476 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003477 "toggleFreeformWindowingMode: No activity record matching token="
3478 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 }
3480
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003481 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003482 if (stack == null) {
3483 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3484 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003485 }
3486
Yunfan Chend967af82019-01-17 18:30:18 +09003487 if (!stack.inFreeformWindowingMode()
3488 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3489 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3490 + "toggle between fullscreen and freeform.");
3491 }
3492
3493 if (stack.inFreeformWindowingMode()) {
3494 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003495 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003496 throw new IllegalStateException("Size-compat windows are currently not"
3497 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003498 } else if (stack.getParent().inFreeformWindowingMode()) {
3499 // If the window is on a freeform display, set it to undefined. It will be
3500 // resolved to freeform and it can adjust windowing mode when the display mode
3501 // changes in runtime.
3502 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003503 } else {
3504 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3505 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003506 } finally {
3507 Binder.restoreCallingIdentity(ident);
3508 }
3509 }
3510 }
3511
3512 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3513 @Override
3514 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003515 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003516 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003517 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003518 }
3519
3520 /** Unregister a task stack listener so that it stops receiving callbacks. */
3521 @Override
3522 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003523 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003524 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003525 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526 }
3527
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 @Override
3529 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3530 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3531 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3532 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3533 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3534 }
3535
3536 @Override
3537 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3538 IBinder activityToken, int flags) {
3539 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3540 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3541 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3542 }
3543
3544 @Override
3545 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3546 Bundle args) {
3547 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3548 true /* focused */, true /* newSessionId */, userHandle, args,
3549 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3550 }
3551
3552 @Override
3553 public Bundle getAssistContextExtras(int requestType) {
3554 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3555 null, null, true /* focused */, true /* newSessionId */,
3556 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3557 if (pae == null) {
3558 return null;
3559 }
3560 synchronized (pae) {
3561 while (!pae.haveResult) {
3562 try {
3563 pae.wait();
3564 } catch (InterruptedException e) {
3565 }
3566 }
3567 }
3568 synchronized (mGlobalLock) {
3569 buildAssistBundleLocked(pae, pae.result);
3570 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003571 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003572 }
3573 return pae.extras;
3574 }
3575
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003576 /**
3577 * Binder IPC calls go through the public entry point.
3578 * This can be called with or without the global lock held.
3579 */
3580 private static int checkCallingPermission(String permission) {
3581 return checkPermission(
3582 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3583 }
3584
3585 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003586 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003587 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3588 mAmInternal.enforceCallingPermission(permission, func);
3589 }
3590 }
3591
3592 @VisibleForTesting
3593 int checkGetTasksPermission(String permission, int pid, int uid) {
3594 return checkPermission(permission, pid, uid);
3595 }
3596
3597 static int checkPermission(String permission, int pid, int uid) {
3598 if (permission == null) {
3599 return PackageManager.PERMISSION_DENIED;
3600 }
3601 return checkComponentPermission(permission, pid, uid, -1, true);
3602 }
3603
Wale Ogunwale214f3482018-10-04 11:00:47 -07003604 public static int checkComponentPermission(String permission, int pid, int uid,
3605 int owningUid, boolean exported) {
3606 return ActivityManagerService.checkComponentPermission(
3607 permission, pid, uid, owningUid, exported);
3608 }
3609
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003610 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3611 if (getRecentTasks().isCallerRecents(callingUid)) {
3612 // Always allow the recents component to get tasks
3613 return true;
3614 }
3615
3616 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3617 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3618 if (!allowed) {
3619 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3620 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3621 // Temporary compatibility: some existing apps on the system image may
3622 // still be requesting the old permission and not switched to the new
3623 // one; if so, we'll still allow them full access. This means we need
3624 // to see if they are holding the old permission and are a system app.
3625 try {
3626 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3627 allowed = true;
3628 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3629 + " is using old GET_TASKS but privileged; allowing");
3630 }
3631 } catch (RemoteException e) {
3632 }
3633 }
3634 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3635 + " does not hold REAL_GET_TASKS; limiting output");
3636 }
3637 return allowed;
3638 }
3639
Nicholas Sauer0259e532019-08-30 08:24:55 -07003640 boolean isCrossUserAllowed(int pid, int uid) {
3641 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3642 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3643 }
3644
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3646 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3647 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3648 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003649 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 "enqueueAssistContext()");
3651
3652 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003653 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 if (activity == null) {
3655 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3656 return null;
3657 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003658 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003659 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3660 return null;
3661 }
3662 if (focused) {
3663 if (activityToken != null) {
3664 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3665 if (activity != caller) {
3666 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3667 + " is not current top " + activity);
3668 return null;
3669 }
3670 }
3671 } else {
3672 activity = ActivityRecord.forTokenLocked(activityToken);
3673 if (activity == null) {
3674 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3675 + " couldn't be found");
3676 return null;
3677 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003678 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003679 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3680 return null;
3681 }
3682 }
3683
3684 PendingAssistExtras pae;
3685 Bundle extras = new Bundle();
3686 if (args != null) {
3687 extras.putAll(args);
3688 }
3689 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003690 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691
3692 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3693 userHandle);
3694 pae.isHome = activity.isActivityTypeHome();
3695
3696 // Increment the sessionId if necessary
3697 if (newSessionId) {
3698 mViSessionId++;
3699 }
3700 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003701 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3702 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003704 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 } catch (RemoteException e) {
3706 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3707 return null;
3708 }
3709 return pae;
3710 }
3711 }
3712
3713 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3714 if (result != null) {
3715 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3716 }
3717 if (pae.hint != null) {
3718 pae.extras.putBoolean(pae.hint, true);
3719 }
3720 }
3721
3722 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3723 IAssistDataReceiver receiver;
3724 synchronized (mGlobalLock) {
3725 mPendingAssistExtras.remove(pae);
3726 receiver = pae.receiver;
3727 }
3728 if (receiver != null) {
3729 // Caller wants result sent back to them.
3730 Bundle sendBundle = new Bundle();
3731 // At least return the receiver extras
3732 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3733 try {
3734 pae.receiver.onHandleAssistData(sendBundle);
3735 } catch (RemoteException e) {
3736 }
3737 }
3738 }
3739
3740 public class PendingAssistExtras extends Binder implements Runnable {
3741 public final ActivityRecord activity;
3742 public boolean isHome;
3743 public final Bundle extras;
3744 public final Intent intent;
3745 public final String hint;
3746 public final IAssistDataReceiver receiver;
3747 public final int userHandle;
3748 public boolean haveResult = false;
3749 public Bundle result = null;
3750 public AssistStructure structure = null;
3751 public AssistContent content = null;
3752 public Bundle receiverExtras;
3753
3754 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3755 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3756 int _userHandle) {
3757 activity = _activity;
3758 extras = _extras;
3759 intent = _intent;
3760 hint = _hint;
3761 receiver = _receiver;
3762 receiverExtras = _receiverExtras;
3763 userHandle = _userHandle;
3764 }
3765
3766 @Override
3767 public void run() {
3768 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3769 synchronized (this) {
3770 haveResult = true;
3771 notifyAll();
3772 }
3773 pendingAssistExtrasTimedOut(this);
3774 }
3775 }
3776
3777 @Override
3778 public boolean isAssistDataAllowedOnCurrentActivity() {
3779 int userId;
3780 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003781 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3783 return false;
3784 }
3785
Wale Ogunwale21e06482019-11-18 05:14:15 -08003786 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003787 if (activity == null) {
3788 return false;
3789 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003790 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 }
3792 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3793 }
3794
3795 @Override
3796 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3797 long ident = Binder.clearCallingIdentity();
3798 try {
3799 synchronized (mGlobalLock) {
3800 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003801 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003802 if (top != caller) {
3803 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3804 + " is not current top " + top);
3805 return false;
3806 }
3807 if (!top.nowVisible) {
3808 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3809 + " is not visible");
3810 return false;
3811 }
3812 }
3813 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3814 token);
3815 } finally {
3816 Binder.restoreCallingIdentity(ident);
3817 }
3818 }
3819
3820 @Override
3821 public boolean isRootVoiceInteraction(IBinder token) {
3822 synchronized (mGlobalLock) {
3823 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3824 if (r == null) {
3825 return false;
3826 }
3827 return r.rootVoiceInteraction;
3828 }
3829 }
3830
Wale Ogunwalef6733932018-06-27 05:14:34 -07003831 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3832 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3833 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3834 if (activityToCallback == null) return;
3835 activityToCallback.setVoiceSessionLocked(voiceSession);
3836
3837 // Inform the activity
3838 try {
3839 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3840 voiceInteractor);
3841 long token = Binder.clearCallingIdentity();
3842 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003843 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003844 } finally {
3845 Binder.restoreCallingIdentity(token);
3846 }
3847 // TODO: VI Should we cache the activity so that it's easier to find later
3848 // rather than scan through all the stacks and activities?
3849 } catch (RemoteException re) {
3850 activityToCallback.clearVoiceSessionLocked();
3851 // TODO: VI Should this terminate the voice session?
3852 }
3853 }
3854
3855 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3856 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3857 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3858 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3859 boolean wasRunningVoice = mRunningVoice != null;
3860 mRunningVoice = session;
3861 if (!wasRunningVoice) {
3862 mVoiceWakeLock.acquire();
3863 updateSleepIfNeededLocked();
3864 }
3865 }
3866 }
3867
3868 void finishRunningVoiceLocked() {
3869 if (mRunningVoice != null) {
3870 mRunningVoice = null;
3871 mVoiceWakeLock.release();
3872 updateSleepIfNeededLocked();
3873 }
3874 }
3875
3876 @Override
3877 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3878 synchronized (mGlobalLock) {
3879 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3880 if (keepAwake) {
3881 mVoiceWakeLock.acquire();
3882 } else {
3883 mVoiceWakeLock.release();
3884 }
3885 }
3886 }
3887 }
3888
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003889 @Override
3890 public ComponentName getActivityClassForToken(IBinder token) {
3891 synchronized (mGlobalLock) {
3892 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3893 if (r == null) {
3894 return null;
3895 }
3896 return r.intent.getComponent();
3897 }
3898 }
3899
3900 @Override
3901 public String getPackageForToken(IBinder token) {
3902 synchronized (mGlobalLock) {
3903 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3904 if (r == null) {
3905 return null;
3906 }
3907 return r.packageName;
3908 }
3909 }
3910
3911 @Override
3912 public void showLockTaskEscapeMessage(IBinder token) {
3913 synchronized (mGlobalLock) {
3914 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3915 if (r == null) {
3916 return;
3917 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003918 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 }
3920 }
3921
3922 @Override
3923 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003924 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 final long token = Binder.clearCallingIdentity();
3926 try {
3927 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003928 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 }
3930 } finally {
3931 Binder.restoreCallingIdentity(token);
3932 }
3933 }
3934
3935 /**
3936 * Try to place task to provided position. The final position might be different depending on
3937 * current user and stacks state. The task will be moved to target stack if it's currently in
3938 * different stack.
3939 */
3940 @Override
3941 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003942 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003943 synchronized (mGlobalLock) {
3944 long ident = Binder.clearCallingIdentity();
3945 try {
3946 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3947 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003948 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003949 if (task == null) {
3950 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3951 + taskId);
3952 }
3953
Louis Chang149d5c82019-12-30 09:47:39 +08003954 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955
3956 if (stack == null) {
3957 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3958 + stackId);
3959 }
3960 if (!stack.isActivityTypeStandardOrUndefined()) {
3961 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3962 + " the position of task " + taskId + " in/to non-standard stack");
3963 }
3964
3965 // TODO: Have the callers of this API call a separate reparent method if that is
3966 // what they intended to do vs. having this method also do reparenting.
3967 if (task.getStack() == stack) {
3968 // Change position in current stack.
3969 stack.positionChildAt(task, position);
3970 } else {
3971 // Reparent to new stack.
3972 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3973 !DEFER_RESUME, "positionTaskInStack");
3974 }
3975 } finally {
3976 Binder.restoreCallingIdentity(ident);
3977 }
3978 }
3979 }
3980
3981 @Override
3982 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3983 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3984 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003985 + Arrays.toString(horizontalSizeConfiguration) + " "
3986 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 synchronized (mGlobalLock) {
3988 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3989 if (record == null) {
3990 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3991 + "found for: " + token);
3992 }
3993 record.setSizeConfigurations(horizontalSizeConfiguration,
3994 verticalSizeConfigurations, smallestSizeConfigurations);
3995 }
3996 }
3997
3998 /**
3999 * Dismisses split-screen multi-window mode.
4000 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4001 */
4002 @Override
4003 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4006 final long ident = Binder.clearCallingIdentity();
4007 try {
4008 synchronized (mGlobalLock) {
4009 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004010 mRootWindowContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004011 if (stack == null) {
4012 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4013 return;
4014 }
4015
4016 if (toTop) {
4017 // Caller wants the current split-screen primary stack to be the top stack after
4018 // it goes fullscreen, so move it to the front.
4019 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004020 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004022 // stack after it goes fullscreen, so we move the focus to the top-most
4023 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4025 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4026 if (otherStack != null) {
4027 otherStack.moveToFront("dismissSplitScreenMode_other");
4028 }
4029 }
4030
Evan Rosky10475742018-09-05 19:02:48 -07004031 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 }
4033 } finally {
4034 Binder.restoreCallingIdentity(ident);
4035 }
4036 }
4037
4038 /**
4039 * Dismisses Pip
4040 * @param animate True if the dismissal should be animated.
4041 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4042 * default animation duration should be used.
4043 */
4044 @Override
4045 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047 final long ident = Binder.clearCallingIdentity();
4048 try {
4049 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004050 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004051 mRootWindowContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004052 if (stack == null) {
4053 Slog.w(TAG, "dismissPip: pinned stack not found.");
4054 return;
4055 }
4056 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4057 throw new IllegalArgumentException("Stack: " + stack
4058 + " doesn't support animated resize.");
4059 }
4060 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004061 stack.animateResizePinnedStack(null /* destBounds */,
4062 null /* sourceHintBounds */, animationDuration,
4063 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004065 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004066 }
4067 }
4068 } finally {
4069 Binder.restoreCallingIdentity(ident);
4070 }
4071 }
4072
4073 @Override
4074 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004075 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 synchronized (mGlobalLock) {
4077 mSuppressResizeConfigChanges = suppress;
4078 }
4079 }
4080
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 @Override
4082 // TODO: API should just be about changing windowing modes...
4083 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004084 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 "moveTasksToFullscreenStack()");
4086 synchronized (mGlobalLock) {
4087 final long origId = Binder.clearCallingIdentity();
4088 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004089 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 if (stack != null){
4091 if (!stack.isActivityTypeStandardOrUndefined()) {
4092 throw new IllegalArgumentException(
4093 "You can't move tasks from non-standard stacks.");
4094 }
4095 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4096 }
4097 } finally {
4098 Binder.restoreCallingIdentity(origId);
4099 }
4100 }
4101 }
4102
4103 /**
4104 * Moves the top activity in the input stackId to the pinned stack.
4105 *
4106 * @param stackId Id of stack to move the top activity to pinned stack.
4107 * @param bounds Bounds to use for pinned stack.
4108 *
4109 * @return True if the top activity of the input stack was successfully moved to the pinned
4110 * stack.
4111 */
4112 @Override
4113 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 "moveTopActivityToPinnedStack()");
4116 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4119 + "Device doesn't support picture-in-picture mode");
4120 }
4121
4122 long ident = Binder.clearCallingIdentity();
4123 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004124 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 } finally {
4126 Binder.restoreCallingIdentity(ident);
4127 }
4128 }
4129 }
4130
4131 @Override
4132 public boolean isInMultiWindowMode(IBinder token) {
4133 final long origId = Binder.clearCallingIdentity();
4134 try {
4135 synchronized (mGlobalLock) {
4136 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4137 if (r == null) {
4138 return false;
4139 }
4140 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4141 return r.inMultiWindowMode();
4142 }
4143 } finally {
4144 Binder.restoreCallingIdentity(origId);
4145 }
4146 }
4147
4148 @Override
4149 public boolean isInPictureInPictureMode(IBinder token) {
4150 final long origId = Binder.clearCallingIdentity();
4151 try {
4152 synchronized (mGlobalLock) {
4153 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4154 }
4155 } finally {
4156 Binder.restoreCallingIdentity(origId);
4157 }
4158 }
4159
4160 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004161 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4162 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004163 return false;
4164 }
4165
4166 // If we are animating to fullscreen then we have already dispatched the PIP mode
4167 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004168 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004169 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 }
4171
4172 @Override
4173 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4174 final long origId = Binder.clearCallingIdentity();
4175 try {
4176 synchronized (mGlobalLock) {
4177 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4178 "enterPictureInPictureMode", token, params);
4179
4180 // If the activity is already in picture in picture mode, then just return early
4181 if (isInPictureInPictureMode(r)) {
4182 return true;
4183 }
4184
4185 // Activity supports picture-in-picture, now check that we can enter PiP at this
4186 // point, if it is
4187 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4188 false /* beforeStopping */)) {
4189 return false;
4190 }
4191
4192 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004193 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004194 if (r.getParent() == null) {
4195 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4196 return;
4197 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004198 // Only update the saved args from the args that are set
4199 r.pictureInPictureArgs.copyOnlySet(params);
4200 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4201 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4202 // Adjust the source bounds by the insets for the transition down
4203 final Rect sourceBounds = new Rect(
4204 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004205 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004206 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004207 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004208 stack.setPictureInPictureAspectRatio(aspectRatio);
4209 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004210 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4211 r.info.applicationInfo.uid, r.shortComponentName,
4212 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004213 logPictureInPictureArgs(params);
4214 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 };
4216
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004217 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 // If the keyguard is showing or occluded, then try and dismiss it before
4219 // entering picture-in-picture (this will prompt the user to authenticate if the
4220 // device is currently locked).
4221 dismissKeyguard(token, new KeyguardDismissCallback() {
4222 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004223 public void onDismissSucceeded() {
4224 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 }
4226 }, null /* message */);
4227 } else {
4228 // Enter picture in picture immediately otherwise
4229 enterPipRunnable.run();
4230 }
4231 return true;
4232 }
4233 } finally {
4234 Binder.restoreCallingIdentity(origId);
4235 }
4236 }
4237
4238 @Override
4239 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4240 final long origId = Binder.clearCallingIdentity();
4241 try {
4242 synchronized (mGlobalLock) {
4243 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4244 "setPictureInPictureParams", token, params);
4245
4246 // Only update the saved args from the args that are set
4247 r.pictureInPictureArgs.copyOnlySet(params);
4248 if (r.inPinnedWindowingMode()) {
4249 // If the activity is already in picture-in-picture, update the pinned stack now
4250 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4251 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004252 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 if (!stack.isAnimatingBoundsToFullscreen()) {
4254 stack.setPictureInPictureAspectRatio(
4255 r.pictureInPictureArgs.getAspectRatio());
4256 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4257 }
4258 }
4259 logPictureInPictureArgs(params);
4260 }
4261 } finally {
4262 Binder.restoreCallingIdentity(origId);
4263 }
4264 }
4265
4266 @Override
4267 public int getMaxNumPictureInPictureActions(IBinder token) {
4268 // Currently, this is a static constant, but later, we may change this to be dependent on
4269 // the context of the activity
4270 return 3;
4271 }
4272
4273 private void logPictureInPictureArgs(PictureInPictureParams params) {
4274 if (params.hasSetActions()) {
4275 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4276 params.getActions().size());
4277 }
4278 if (params.hasSetAspectRatio()) {
4279 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4280 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4281 MetricsLogger.action(lm);
4282 }
4283 }
4284
4285 /**
4286 * Checks the state of the system and the activity associated with the given {@param token} to
4287 * verify that picture-in-picture is supported for that activity.
4288 *
4289 * @return the activity record for the given {@param token} if all the checks pass.
4290 */
4291 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4292 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 throw new IllegalStateException(caller
4295 + ": Device doesn't support picture-in-picture mode.");
4296 }
4297
4298 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4299 if (r == null) {
4300 throw new IllegalStateException(caller
4301 + ": Can't find activity for token=" + token);
4302 }
4303
4304 if (!r.supportsPictureInPicture()) {
4305 throw new IllegalStateException(caller
4306 + ": Current activity does not support picture-in-picture.");
4307 }
4308
4309 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004310 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08004311 r.getDisplayId(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 final float minAspectRatio = mContext.getResources().getFloat(
4313 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4314 final float maxAspectRatio = mContext.getResources().getFloat(
4315 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4316 throw new IllegalArgumentException(String.format(caller
4317 + ": Aspect ratio is too extreme (must be between %f and %f).",
4318 minAspectRatio, maxAspectRatio));
4319 }
4320
4321 // Truncate the number of actions if necessary
4322 params.truncateActions(getMaxNumPictureInPictureActions(token));
4323
4324 return r;
4325 }
4326
4327 @Override
4328 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004329 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 synchronized (mGlobalLock) {
4331 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4332 if (r == null) {
4333 throw new IllegalArgumentException("Activity does not exist; token="
4334 + activityToken);
4335 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004336 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004337 }
4338 }
4339
4340 @Override
4341 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4342 Rect tempDockedTaskInsetBounds,
4343 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004344 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004345 long ident = Binder.clearCallingIdentity();
4346 try {
4347 synchronized (mGlobalLock) {
4348 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4349 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4350 PRESERVE_WINDOWS);
4351 }
4352 } finally {
4353 Binder.restoreCallingIdentity(ident);
4354 }
4355 }
4356
4357 @Override
4358 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 final long ident = Binder.clearCallingIdentity();
4361 try {
4362 synchronized (mGlobalLock) {
4363 mStackSupervisor.setSplitScreenResizing(resizing);
4364 }
4365 } finally {
4366 Binder.restoreCallingIdentity(ident);
4367 }
4368 }
4369
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004370 /**
4371 * Check that we have the features required for VR-related API calls, and throw an exception if
4372 * not.
4373 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004374 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 if (!mContext.getPackageManager().hasSystemFeature(
4376 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4377 throw new UnsupportedOperationException("VR mode not supported on this device!");
4378 }
4379 }
4380
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 @Override
4382 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004383 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384
4385 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4386
4387 ActivityRecord r;
4388 synchronized (mGlobalLock) {
4389 r = ActivityRecord.isInStackLocked(token);
4390 }
4391
4392 if (r == null) {
4393 throw new IllegalArgumentException();
4394 }
4395
4396 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004397 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 VrManagerInternal.NO_ERROR) {
4399 return err;
4400 }
4401
4402 // Clear the binder calling uid since this path may call moveToTask().
4403 final long callingId = Binder.clearCallingIdentity();
4404 try {
4405 synchronized (mGlobalLock) {
4406 r.requestedVrComponent = (enabled) ? packageName : null;
4407
4408 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004409 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004410 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 }
4412 return 0;
4413 }
4414 } finally {
4415 Binder.restoreCallingIdentity(callingId);
4416 }
4417 }
4418
4419 @Override
4420 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4421 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4422 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004423 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4425 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4426 }
Louis Changcdec0802019-11-11 11:45:07 +08004427 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 || activity.voiceSession != null) {
4429 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4430 return;
4431 }
4432 if (activity.pendingVoiceInteractionStart) {
4433 Slog.w(TAG, "Pending start of voice interaction already.");
4434 return;
4435 }
4436 activity.pendingVoiceInteractionStart = true;
4437 }
4438 LocalServices.getService(VoiceInteractionManagerInternal.class)
4439 .startLocalVoiceInteraction(callingActivity, options);
4440 }
4441
4442 @Override
4443 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4444 LocalServices.getService(VoiceInteractionManagerInternal.class)
4445 .stopLocalVoiceInteraction(callingActivity);
4446 }
4447
4448 @Override
4449 public boolean supportsLocalVoiceInteraction() {
4450 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4451 .supportsLocalVoiceInteraction();
4452 }
4453
4454 /** Notifies all listeners when the pinned stack animation starts. */
4455 @Override
4456 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004457 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 }
4459
4460 /** Notifies all listeners when the pinned stack animation ends. */
4461 @Override
4462 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004463 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464 }
4465
4466 @Override
4467 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004468 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 final long ident = Binder.clearCallingIdentity();
4470 try {
4471 synchronized (mGlobalLock) {
4472 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4473 }
4474 } finally {
4475 Binder.restoreCallingIdentity(ident);
4476 }
4477 }
4478
4479 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004481 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004482
4483 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004484 if (mWindowManager == null) {
4485 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4486 return false;
4487 }
4488
4489 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004490 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004491 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 }
4493
Riddle Hsua0022cd2019-09-09 21:12:41 +08004494 mH.sendMessage(PooledLambda.obtainMessage(
4495 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4496 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497
4498 final long origId = Binder.clearCallingIdentity();
4499 try {
4500 if (values != null) {
4501 Settings.System.clearConfiguration(values);
4502 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004504 UserHandle.USER_NULL, false /* deferResume */,
4505 mTmpUpdateConfigurationResult);
4506 return mTmpUpdateConfigurationResult.changes != 0;
4507 } finally {
4508 Binder.restoreCallingIdentity(origId);
4509 }
4510 }
4511 }
4512
4513 @Override
4514 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4515 CharSequence message) {
4516 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004517 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004518 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4519 }
4520 final long callingId = Binder.clearCallingIdentity();
4521 try {
4522 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004523 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004524 }
4525 } finally {
4526 Binder.restoreCallingIdentity(callingId);
4527 }
4528 }
4529
4530 @Override
4531 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004532 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004533 "cancelTaskWindowTransition()");
4534 final long ident = Binder.clearCallingIdentity();
4535 try {
4536 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004537 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 MATCH_TASK_IN_STACKS_ONLY);
4539 if (task == null) {
4540 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4541 return;
4542 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004543 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 }
4545 } finally {
4546 Binder.restoreCallingIdentity(ident);
4547 }
4548 }
4549
4550 @Override
4551 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004552 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 final long ident = Binder.clearCallingIdentity();
4554 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004555 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 } finally {
4557 Binder.restoreCallingIdentity(ident);
4558 }
4559 }
4560
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004561 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4562 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004563 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004564 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004565 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004566 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4567 if (task == null) {
4568 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4569 return null;
4570 }
4571 }
4572 // Don't call this while holding the lock as this operation might hit the disk.
4573 return task.getSnapshot(reducedResolution, restoreFromDisk);
4574 }
4575
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004576 @Override
4577 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4578 synchronized (mGlobalLock) {
4579 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4580 if (r == null) {
4581 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4582 + token);
4583 return;
4584 }
4585 final long origId = Binder.clearCallingIdentity();
4586 try {
4587 r.setDisablePreviewScreenshots(disable);
4588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592 }
4593
Riddle Hsu440f88b2019-11-06 22:17:35 +08004594 @Override
4595 public void invalidateHomeTaskSnapshot(IBinder token) {
4596 synchronized (mGlobalLock) {
4597 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4598 if (r == null || !r.isActivityTypeHome()) {
4599 return;
4600 }
4601 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4602 }
4603 }
4604
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004605 /** Return the user id of the last resumed activity. */
4606 @Override
4607 public @UserIdInt
4608 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004609 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004610 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4611 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004612 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004613 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004614 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004615 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004616 }
4617 }
4618
4619 @Override
4620 public void updateLockTaskFeatures(int userId, int flags) {
4621 final int callingUid = Binder.getCallingUid();
4622 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004623 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004624 "updateLockTaskFeatures()");
4625 }
4626 synchronized (mGlobalLock) {
4627 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4628 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004629 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 }
4631 }
4632
4633 @Override
4634 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4635 synchronized (mGlobalLock) {
4636 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4637 if (r == null) {
4638 return;
4639 }
4640 final long origId = Binder.clearCallingIdentity();
4641 try {
4642 r.setShowWhenLocked(showWhenLocked);
4643 } finally {
4644 Binder.restoreCallingIdentity(origId);
4645 }
4646 }
4647 }
4648
4649 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004650 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4651 synchronized (mGlobalLock) {
4652 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4653 if (r == null) {
4654 return;
4655 }
4656 final long origId = Binder.clearCallingIdentity();
4657 try {
4658 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4659 } finally {
4660 Binder.restoreCallingIdentity(origId);
4661 }
4662 }
4663 }
4664
4665 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004666 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4667 synchronized (mGlobalLock) {
4668 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4669 if (r == null) {
4670 return;
4671 }
4672 final long origId = Binder.clearCallingIdentity();
4673 try {
4674 r.setTurnScreenOn(turnScreenOn);
4675 } finally {
4676 Binder.restoreCallingIdentity(origId);
4677 }
4678 }
4679 }
4680
4681 @Override
4682 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004683 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004684 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004685 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004686 synchronized (mGlobalLock) {
4687 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4688 if (r == null) {
4689 return;
4690 }
4691 final long origId = Binder.clearCallingIdentity();
4692 try {
4693 r.registerRemoteAnimations(definition);
4694 } finally {
4695 Binder.restoreCallingIdentity(origId);
4696 }
4697 }
4698 }
4699
4700 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004701 public void unregisterRemoteAnimations(IBinder token) {
4702 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4703 "unregisterRemoteAnimations");
4704 synchronized (mGlobalLock) {
4705 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4706 if (r == null) {
4707 return;
4708 }
4709 final long origId = Binder.clearCallingIdentity();
4710 try {
4711 r.unregisterRemoteAnimations();
4712 } finally {
4713 Binder.restoreCallingIdentity(origId);
4714 }
4715 }
4716 }
4717
4718 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004719 public void registerRemoteAnimationForNextActivityStart(String packageName,
4720 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004721 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004722 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004723 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004724 synchronized (mGlobalLock) {
4725 final long origId = Binder.clearCallingIdentity();
4726 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004727 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004728 packageName, adapter);
4729 } finally {
4730 Binder.restoreCallingIdentity(origId);
4731 }
4732 }
4733 }
4734
Evan Rosky966759f2019-01-15 10:33:58 -08004735 @Override
4736 public void registerRemoteAnimationsForDisplay(int displayId,
4737 RemoteAnimationDefinition definition) {
4738 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4739 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004740 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004741 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004742 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004743 if (display == null) {
4744 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4745 return;
4746 }
4747 final long origId = Binder.clearCallingIdentity();
4748 try {
4749 display.mDisplayContent.registerRemoteAnimations(definition);
4750 } finally {
4751 Binder.restoreCallingIdentity(origId);
4752 }
4753 }
4754 }
4755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004756 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4757 @Override
4758 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4759 synchronized (mGlobalLock) {
4760 final long origId = Binder.clearCallingIdentity();
4761 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004762 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004763 } finally {
4764 Binder.restoreCallingIdentity(origId);
4765 }
4766 }
4767 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004768
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004769 @Override
4770 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004771 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004772 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004773 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004774 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004775 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004776 }
4777 }
4778
4779 @Override
4780 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004781 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004782 != PERMISSION_GRANTED) {
4783 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4784 + Binder.getCallingPid()
4785 + ", uid=" + Binder.getCallingUid()
4786 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4787 Slog.w(TAG, msg);
4788 throw new SecurityException(msg);
4789 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004790 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004792 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004793 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004794 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 }
4796 }
4797
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004798 @Override
4799 public void stopAppSwitches() {
4800 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4801 synchronized (mGlobalLock) {
4802 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004803 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004804 mDidAppSwitch = false;
4805 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4806 }
4807 }
4808
4809 @Override
4810 public void resumeAppSwitches() {
4811 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4812 synchronized (mGlobalLock) {
4813 // Note that we don't execute any pending app switches... we will
4814 // let those wait until either the timeout, or the next start
4815 // activity request.
4816 mAppSwitchesAllowedTime = 0;
4817 }
4818 }
4819
Ricky Wai906af482019-06-03 17:25:28 +01004820 long getLastStopAppSwitchesTime() {
4821 return mLastStopAppSwitchesTime;
4822 }
4823
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004824 void onStartActivitySetDidAppSwitch() {
4825 if (mDidAppSwitch) {
4826 // This is the second allowed switch since we stopped switches, so now just generally
4827 // allow switches. Use case:
4828 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4829 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4830 // anyone to switch again).
4831 mAppSwitchesAllowedTime = 0;
4832 } else {
4833 mDidAppSwitch = true;
4834 }
4835 }
4836
4837 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004838 boolean shouldDisableNonVrUiLocked() {
4839 return mVrController.shouldDisableNonVrUiLocked();
4840 }
4841
Wale Ogunwale53783742018-09-16 10:21:51 -07004842 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004843 // 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 +00004844 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004845 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004846 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4847 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004848 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004849 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004850 }
4851 mH.post(() -> {
4852 if (!mVrController.onVrModeChanged(r)) {
4853 return;
4854 }
4855 synchronized (mGlobalLock) {
4856 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4857 mWindowManager.disableNonVrUi(disableNonVrUi);
4858 if (disableNonVrUi) {
4859 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4860 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004861 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004862 }
4863 }
4864 });
4865 }
4866
Wale Ogunwale53783742018-09-16 10:21:51 -07004867 @Override
4868 public int getPackageScreenCompatMode(String packageName) {
4869 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4870 synchronized (mGlobalLock) {
4871 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4872 }
4873 }
4874
4875 @Override
4876 public void setPackageScreenCompatMode(String packageName, int mode) {
4877 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4878 "setPackageScreenCompatMode");
4879 synchronized (mGlobalLock) {
4880 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4881 }
4882 }
4883
4884 @Override
4885 public boolean getPackageAskScreenCompat(String packageName) {
4886 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4887 synchronized (mGlobalLock) {
4888 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4889 }
4890 }
4891
4892 @Override
4893 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4894 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4895 "setPackageAskScreenCompat");
4896 synchronized (mGlobalLock) {
4897 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4898 }
4899 }
4900
Wale Ogunwale64258362018-10-16 15:13:37 -07004901 public static String relaunchReasonToString(int relaunchReason) {
4902 switch (relaunchReason) {
4903 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4904 return "window_resize";
4905 case RELAUNCH_REASON_FREE_RESIZE:
4906 return "free_resize";
4907 default:
4908 return null;
4909 }
4910 }
4911
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004912 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004913 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004914 }
4915
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004916 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004917 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004918 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4919 }
4920
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004921 boolean isKeyguardLocked() {
4922 return mKeyguardController.isKeyguardLocked();
4923 }
4924
Garfield Tan01548632018-11-27 10:15:48 -08004925 /**
4926 * Clears launch params for the given package.
4927 * @param packageNames the names of the packages of which the launch params are to be cleared
4928 */
4929 @Override
4930 public void clearLaunchParamsForPackages(List<String> packageNames) {
4931 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4932 "clearLaunchParamsForPackages");
4933 synchronized (mGlobalLock) {
4934 for (int i = 0; i < packageNames.size(); ++i) {
4935 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4936 }
4937 }
4938 }
4939
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004940 /**
4941 * Makes the display with the given id a single task instance display. I.e the display can only
4942 * contain one task.
4943 */
4944 @Override
4945 public void setDisplayToSingleTaskInstance(int displayId) {
4946 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4947 "setDisplayToSingleTaskInstance");
4948 final long origId = Binder.clearCallingIdentity();
4949 try {
Louis Chang677921f2019-12-06 16:44:24 +08004950 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004951 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004952 if (display != null) {
4953 display.setDisplayToSingleTaskInstance();
4954 }
4955 } finally {
4956 Binder.restoreCallingIdentity(origId);
4957 }
4958 }
4959
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004960 /**
4961 * Requests that an activity should enter picture-in-picture mode if possible.
4962 */
4963 @Override
4964 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4965 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4966 "requestPictureInPictureMode");
4967 final long origId = Binder.clearCallingIdentity();
4968 try {
4969 synchronized (mGlobalLock) {
4970 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4971 if (activity == null) {
4972 return;
4973 }
4974
4975 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4976 "requestPictureInPictureMode", /* beforeStopping */ false);
4977 if (!canEnterPictureInPicture) {
4978 throw new IllegalStateException(
4979 "Requested PIP on an activity that doesn't support it");
4980 }
4981
4982 try {
4983 final ClientTransaction transaction = ClientTransaction.obtain(
4984 activity.app.getThread(),
4985 activity.token);
4986 transaction.addCallback(EnterPipRequestedItem.obtain());
4987 getLifecycleManager().scheduleTransaction(transaction);
4988 } catch (Exception e) {
4989 Slog.w(TAG, "Failed to send enter pip requested item: "
4990 + activity.intent.getComponent(), e);
4991 }
4992 }
4993 } finally {
4994 Binder.restoreCallingIdentity(origId);
4995 }
4996 }
4997
Wale Ogunwale31913b52018-10-13 08:29:31 -07004998 void dumpLastANRLocked(PrintWriter pw) {
4999 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5000 if (mLastANRState == null) {
5001 pw.println(" <no ANR has occurred since boot>");
5002 } else {
5003 pw.println(mLastANRState);
5004 }
5005 }
5006
5007 void dumpLastANRTracesLocked(PrintWriter pw) {
5008 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5009
5010 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5011 if (ArrayUtils.isEmpty(files)) {
5012 pw.println(" <no ANR has occurred since boot>");
5013 return;
5014 }
5015 // Find the latest file.
5016 File latest = null;
5017 for (File f : files) {
5018 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5019 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005020 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005021 }
5022 pw.print("File: ");
5023 pw.print(latest.getName());
5024 pw.println();
5025 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5026 String line;
5027 while ((line = in.readLine()) != null) {
5028 pw.println(line);
5029 }
5030 } catch (IOException e) {
5031 pw.print("Unable to read: ");
5032 pw.print(e);
5033 pw.println();
5034 }
5035 }
5036
5037 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5038 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5039 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5040 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5041 }
5042
5043 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5044 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5045 pw.println(header);
5046
Louis Chang149d5c82019-12-30 09:47:39 +08005047 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005048 dumpPackage);
5049 boolean needSep = printedAnything;
5050
5051 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005052 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005053 " ResumedActivity: ");
5054 if (printed) {
5055 printedAnything = true;
5056 needSep = false;
5057 }
5058
5059 if (dumpPackage == null) {
5060 if (needSep) {
5061 pw.println();
5062 }
5063 printedAnything = true;
5064 mStackSupervisor.dump(pw, " ");
5065 }
5066
5067 if (!printedAnything) {
5068 pw.println(" (nothing)");
5069 }
5070 }
5071
5072 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005073 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005074 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005075 pw.println(" ");
5076 }
5077
5078 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5079 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5080 getActivityStartController().dump(pw, "", dumpPackage);
5081 }
5082
5083 /**
5084 * There are three things that cmd can be:
5085 * - a flattened component name that matches an existing activity
5086 * - the cmd arg isn't the flattened component name of an existing activity:
5087 * dump all activity whose component contains the cmd as a substring
5088 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005089 * <p>
5090 * The caller should not hold lock when calling this method because it will wait for the
5091 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005092 *
5093 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5094 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5095 */
5096 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5097 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5098 ArrayList<ActivityRecord> activities;
5099
5100 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005101 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005102 dumpFocusedStackOnly);
5103 }
5104
5105 if (activities.size() <= 0) {
5106 return false;
5107 }
5108
5109 String[] newArgs = new String[args.length - opti];
5110 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5111
Louis Changcdec0802019-11-11 11:45:07 +08005112 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005113 boolean needSep = false;
5114 for (int i = activities.size() - 1; i >= 0; i--) {
5115 ActivityRecord r = activities.get(i);
5116 if (needSep) {
5117 pw.println();
5118 }
5119 needSep = true;
5120 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005121 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005122 if (lastTask != task) {
5123 lastTask = task;
5124 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005125 pw.print(" id="); pw.print(lastTask.mTaskId);
5126 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005127 if (dumpAll) {
5128 lastTask.dump(pw, " ");
5129 }
5130 }
5131 }
5132 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5133 }
5134 return true;
5135 }
5136
5137 /**
5138 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5139 * there is a thread associated with the activity.
5140 */
5141 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5142 final ActivityRecord r, String[] args, boolean dumpAll) {
5143 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005144 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005145 synchronized (mGlobalLock) {
5146 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5147 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5148 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005149 if (r.hasProcess()) {
5150 pw.println(r.app.getPid());
5151 appThread = r.app.getThread();
5152 } else {
5153 pw.println("(not running)");
5154 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005155 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005156 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005157 }
5158 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005159 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005160 // flush anything that is already in the PrintWriter since the thread is going
5161 // to write to the file descriptor directly
5162 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005163 try (TransferPipe tp = new TransferPipe()) {
5164 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5165 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005166 } catch (IOException e) {
5167 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5168 } catch (RemoteException e) {
5169 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5170 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005171 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005172 }
5173
sanryhuang498e77e2018-12-06 14:57:01 +08005174 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5175 boolean testPssMode) {
5176 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5177 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5178 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005179 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005180 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5181 st.toString());
5182 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005183 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5184 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5185 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005186 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5187 testPssMode);
5188 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005189 }
5190
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005191 int getCurrentUserId() {
5192 return mAmInternal.getCurrentUserId();
5193 }
5194
5195 private void enforceNotIsolatedCaller(String caller) {
5196 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5197 throw new SecurityException("Isolated process not allowed to call " + caller);
5198 }
5199 }
5200
Wale Ogunwalef6733932018-06-27 05:14:34 -07005201 public Configuration getConfiguration() {
5202 Configuration ci;
5203 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005204 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005205 ci.userSetLocale = false;
5206 }
5207 return ci;
5208 }
5209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 /**
5211 * Current global configuration information. Contains general settings for the entire system,
5212 * also corresponds to the merged configuration of the default display.
5213 */
5214 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005215 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005216 // while initializing process record for system, see {@link
5217 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005218 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005219 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
5222 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5223 boolean initLocale) {
5224 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5225 }
5226
5227 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5228 boolean initLocale, boolean deferResume) {
5229 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5230 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5231 UserHandle.USER_NULL, deferResume);
5232 }
5233
Wale Ogunwale59507092018-10-29 09:00:30 -07005234 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235 final long origId = Binder.clearCallingIdentity();
5236 try {
5237 synchronized (mGlobalLock) {
5238 updateConfigurationLocked(values, null, false, true, userId,
5239 false /* deferResume */);
5240 }
5241 } finally {
5242 Binder.restoreCallingIdentity(origId);
5243 }
5244 }
5245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5247 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5248 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5249 deferResume, null /* result */);
5250 }
5251
5252 /**
5253 * Do either or both things: (1) change the current configuration, and (2)
5254 * make sure the given activity is running with the (now) current
5255 * configuration. Returns true if the activity has been left running, or
5256 * false if <var>starting</var> is being destroyed to match the new
5257 * configuration.
5258 *
5259 * @param userId is only used when persistent parameter is set to true to persist configuration
5260 * for that particular user
5261 */
5262 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5263 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5264 ActivityTaskManagerService.UpdateConfigurationResult result) {
5265 int changes = 0;
5266 boolean kept = true;
5267
Riddle Hsua0022cd2019-09-09 21:12:41 +08005268 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269 try {
5270 if (values != null) {
5271 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5272 deferResume);
5273 }
5274
5275 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5276 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005277 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 }
5279
5280 if (result != null) {
5281 result.changes = changes;
5282 result.activityRelaunched = !kept;
5283 }
5284 return kept;
5285 }
5286
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005288 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005290
Louis Chang677921f2019-12-06 16:44:24 +08005291 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005292 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005293
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 mTempConfig.setTo(getGlobalConfiguration());
5295 final int changes = mTempConfig.updateFrom(values);
5296 if (changes == 0) {
5297 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5298 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5299 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5300 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005301 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302 return 0;
5303 }
5304
5305 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5306 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005307 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005308 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5309 values.colorMode,
5310 values.densityDpi,
5311 values.fontScale,
5312 values.hardKeyboardHidden,
5313 values.keyboard,
5314 values.keyboardHidden,
5315 values.mcc,
5316 values.mnc,
5317 values.navigation,
5318 values.navigationHidden,
5319 values.orientation,
5320 values.screenHeightDp,
5321 values.screenLayout,
5322 values.screenWidthDp,
5323 values.smallestScreenWidthDp,
5324 values.touchscreen,
5325 values.uiMode);
5326
5327
5328 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5329 final LocaleList locales = values.getLocales();
5330 int bestLocaleIndex = 0;
5331 if (locales.size() > 1) {
5332 if (mSupportedSystemLocales == null) {
5333 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5334 }
5335 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5336 }
5337 SystemProperties.set("persist.sys.locale",
5338 locales.get(bestLocaleIndex).toLanguageTag());
5339 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005340
5341 final Message m = PooledLambda.obtainMessage(
5342 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5343 locales.get(bestLocaleIndex));
5344 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005345 }
5346
Yunfan Chen75157d72018-07-27 14:47:21 +09005347 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005348
5349 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005350 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
5352 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5353 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005354 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005355
5356 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005357 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005358
5359 AttributeCache ac = AttributeCache.instance();
5360 if (ac != null) {
5361 ac.updateConfiguration(mTempConfig);
5362 }
5363
5364 // Make sure all resources in our process are updated right now, so that anyone who is going
5365 // to retrieve resource values after we return will be sure to get the new ones. This is
5366 // especially important during boot, where the first config change needs to guarantee all
5367 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005368 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369
5370 // We need another copy of global config because we're scheduling some calls instead of
5371 // running them in place. We need to be sure that object we send will be handled unchanged.
5372 final Configuration configCopy = new Configuration(mTempConfig);
5373 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005374 final Message msg = PooledLambda.obtainMessage(
5375 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5376 this, userId, configCopy);
5377 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005378 }
5379
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005380 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5381 for (int i = pidMap.size() - 1; i >= 0; i--) {
5382 final int pid = pidMap.keyAt(i);
5383 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005384 if (DEBUG_CONFIGURATION) {
5385 Slog.v(TAG_CONFIGURATION, "Update process config of "
5386 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005387 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005388 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005389 }
5390
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005391 final Message msg = PooledLambda.obtainMessage(
5392 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5393 mAmInternal, changes, initLocale);
5394 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005395
5396 // Override configuration of the default display duplicates global config, so we need to
5397 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005398 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005399 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005400
5401 return changes;
5402 }
5403
Riddle Hsua0022cd2019-09-09 21:12:41 +08005404 /** @see WindowSurfacePlacer#deferLayout */
5405 void deferWindowLayout() {
5406 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5407 // Reset the reasons at the first entrance because we only care about the changes in the
5408 // deferred scope.
5409 mLayoutReasons = 0;
5410 }
5411
5412 mWindowManager.mWindowPlacerLocked.deferLayout();
5413 }
5414
5415 /** @see WindowSurfacePlacer#continueLayout */
5416 void continueWindowLayout() {
5417 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5418 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5419 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5420 }
5421 }
5422
5423 /**
5424 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5425 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5426 * defer count is gone.
5427 */
5428 void addWindowLayoutReasons(@LayoutReason int reasons) {
5429 mLayoutReasons |= reasons;
5430 }
5431
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 private void updateEventDispatchingLocked(boolean booted) {
5433 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5434 }
5435
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005436 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5437 final ContentResolver resolver = mContext.getContentResolver();
5438 Settings.System.putConfigurationForUser(resolver, config, userId);
5439 }
5440
5441 private void sendLocaleToMountDaemonMsg(Locale l) {
5442 try {
5443 IBinder service = ServiceManager.getService("mount");
5444 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5445 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5446 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5447 } catch (RemoteException e) {
5448 Log.e(TAG, "Error storing locale for decryption UI", e);
5449 }
5450 }
5451
Alison Cichowlas3e340502018-08-07 17:15:01 -04005452 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5453 mStartActivitySources.remove(permissionToken);
5454 mExpiredStartAsCallerTokens.add(permissionToken);
5455 }
5456
5457 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5458 mExpiredStartAsCallerTokens.remove(permissionToken);
5459 }
5460
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005461 boolean isActivityStartsLoggingEnabled() {
5462 return mAmInternal.isActivityStartsLoggingEnabled();
5463 }
5464
Michal Karpinski8596ded2018-11-14 14:43:48 +00005465 boolean isBackgroundActivityStartsEnabled() {
5466 return mAmInternal.isBackgroundActivityStartsEnabled();
5467 }
5468
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005470 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005471 mWindowManager.enableScreenAfterBoot();
5472
5473 synchronized (mGlobalLock) {
5474 updateEventDispatchingLocked(booted);
5475 }
5476 }
5477
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005478 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5479 if (r == null || !r.hasProcess()) {
5480 return KEY_DISPATCHING_TIMEOUT_MS;
5481 }
5482 return getInputDispatchingTimeoutLocked(r.app);
5483 }
5484
5485 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005486 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005487 }
5488
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 /**
5490 * Decide based on the configuration whether we should show the ANR,
5491 * crash, etc dialogs. The idea is that if there is no affordance to
5492 * press the on-screen buttons, or the user experience would be more
5493 * greatly impacted than the crash itself, we shouldn't show the dialog.
5494 *
5495 * A thought: SystemUI might also want to get told about this, the Power
5496 * dialog / global actions also might want different behaviors.
5497 */
5498 private void updateShouldShowDialogsLocked(Configuration config) {
5499 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5500 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5501 && config.navigation == Configuration.NAVIGATION_NONAV);
5502 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5503 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5504 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5505 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5506 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5507 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5508 HIDE_ERROR_DIALOGS, 0) != 0;
5509 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5510 }
5511
5512 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5513 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5514 FONT_SCALE, 1.0f, userId);
5515
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005516 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 if (getGlobalConfiguration().fontScale == scaleFactor) {
5518 return;
5519 }
5520
5521 final Configuration configuration
5522 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5523 configuration.fontScale = scaleFactor;
5524 updatePersistentConfiguration(configuration, userId);
5525 }
5526 }
5527
5528 // Actually is sleeping or shutting down or whatever else in the future
5529 // is an inactive state.
5530 boolean isSleepingOrShuttingDownLocked() {
5531 return isSleepingLocked() || mShuttingDown;
5532 }
5533
5534 boolean isSleepingLocked() {
5535 return mSleeping;
5536 }
5537
Riddle Hsu16567132018-08-16 21:37:47 +08005538 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005540 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541 if (task.isActivityTypeStandard()) {
5542 if (mCurAppTimeTracker != r.appTimeTracker) {
5543 // We are switching app tracking. Complete the current one.
5544 if (mCurAppTimeTracker != null) {
5545 mCurAppTimeTracker.stop();
5546 mH.obtainMessage(
5547 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005548 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 mCurAppTimeTracker = null;
5550 }
5551 if (r.appTimeTracker != null) {
5552 mCurAppTimeTracker = r.appTimeTracker;
5553 startTimeTrackingFocusedActivityLocked();
5554 }
5555 } else {
5556 startTimeTrackingFocusedActivityLocked();
5557 }
5558 } else {
5559 r.appTimeTracker = null;
5560 }
5561 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5562 // TODO: Probably not, because we don't want to resume voice on switching
5563 // back to this activity
5564 if (task.voiceInteractor != null) {
5565 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5566 } else {
5567 finishRunningVoiceLocked();
5568
5569 if (mLastResumedActivity != null) {
5570 final IVoiceInteractionSession session;
5571
Louis Changcdec0802019-11-11 11:45:07 +08005572 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005573 if (lastResumedActivityTask != null
5574 && lastResumedActivityTask.voiceSession != null) {
5575 session = lastResumedActivityTask.voiceSession;
5576 } else {
5577 session = mLastResumedActivity.voiceSession;
5578 }
5579
5580 if (session != null) {
5581 // We had been in a voice interaction session, but now focused has
5582 // move to something different. Just finish the session, we can't
5583 // return to it and retain the proper state and synchronization with
5584 // the voice interaction service.
5585 finishVoiceTask(session);
5586 }
5587 }
5588 }
5589
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005590 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5591 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 }
5593 updateResumedAppTrace(r);
5594 mLastResumedActivity = r;
5595
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005596 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597
5598 applyUpdateLockStateLocked(r);
5599 applyUpdateVrModeLocked(r);
5600
Jeff Changd136e772019-11-05 20:33:52 +08005601 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005602 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 r == null ? "NULL" : r.shortComponentName,
5604 reason);
5605 }
5606
5607 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5608 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005609 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005610 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005611 updateSleepIfNeededLocked();
5612 return token;
5613 }
5614 }
5615
5616 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005617 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005618 final boolean wasSleeping = mSleeping;
5619 boolean updateOomAdj = false;
5620
5621 if (!shouldSleep) {
5622 // If wasSleeping is true, we need to wake up activity manager state from when
5623 // we started sleeping. In either case, we need to apply the sleep tokens, which
5624 // will wake up stacks or put them to sleep as appropriate.
5625 if (wasSleeping) {
5626 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005627 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5628 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005629 startTimeTrackingFocusedActivityLocked();
5630 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005631 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005632 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5633 }
Louis Chang149d5c82019-12-30 09:47:39 +08005634 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005635 if (wasSleeping) {
5636 updateOomAdj = true;
5637 }
5638 } else if (!mSleeping && shouldSleep) {
5639 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005640 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5641 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005642 if (mCurAppTimeTracker != null) {
5643 mCurAppTimeTracker.stop();
5644 }
5645 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005646 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005647 mStackSupervisor.goingToSleepLocked();
5648 updateResumedAppTrace(null /* resumed */);
5649 updateOomAdj = true;
5650 }
5651 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005652 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005653 }
5654 }
5655
5656 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005657 mH.removeCallbacks(mUpdateOomAdjRunnable);
5658 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005659 }
5660
Wale Ogunwale53783742018-09-16 10:21:51 -07005661 void updateCpuStats() {
5662 mH.post(mAmInternal::updateCpuStats);
5663 }
5664
Hui Yu03d12402018-12-06 18:00:37 -08005665 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5666 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005667 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5668 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005669 mH.sendMessage(m);
5670 }
5671
Hui Yu03d12402018-12-06 18:00:37 -08005672 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005673 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005674 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005675 if (task != null) {
5676 final ActivityRecord rootActivity = task.getRootActivity();
5677 if (rootActivity != null) {
5678 taskRoot = rootActivity.mActivityComponent;
5679 }
5680 }
5681
Hui Yu03d12402018-12-06 18:00:37 -08005682 final Message m = PooledLambda.obtainMessage(
5683 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005684 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005685 mH.sendMessage(m);
5686 }
5687
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005688 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5689 String hostingType) {
5690 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005691 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5692 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005693 + activity.processName);
5694 }
5695 // Post message to start process to avoid possible deadlock of calling into AMS with the
5696 // ATMS lock held.
5697 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5698 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5699 isTop, hostingType, activity.intent.getComponent());
5700 mH.sendMessage(m);
5701 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005702 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005703 }
5704 }
5705
Wale Ogunwale53783742018-09-16 10:21:51 -07005706 void setBooting(boolean booting) {
5707 mAmInternal.setBooting(booting);
5708 }
5709
5710 boolean isBooting() {
5711 return mAmInternal.isBooting();
5712 }
5713
5714 void setBooted(boolean booted) {
5715 mAmInternal.setBooted(booted);
5716 }
5717
5718 boolean isBooted() {
5719 return mAmInternal.isBooted();
5720 }
5721
5722 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5723 mH.post(() -> {
5724 if (finishBooting) {
5725 mAmInternal.finishBooting();
5726 }
5727 if (enableScreen) {
5728 mInternal.enableScreenAfterBoot(isBooted());
5729 }
5730 });
5731 }
5732
5733 void setHeavyWeightProcess(ActivityRecord root) {
5734 mHeavyWeightProcess = root.app;
5735 final Message m = PooledLambda.obtainMessage(
5736 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005737 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005738 mH.sendMessage(m);
5739 }
5740
5741 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5742 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5743 return;
5744 }
5745
5746 mHeavyWeightProcess = null;
5747 final Message m = PooledLambda.obtainMessage(
5748 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5749 proc.mUserId);
5750 mH.sendMessage(m);
5751 }
5752
5753 private void cancelHeavyWeightProcessNotification(int userId) {
5754 final INotificationManager inm = NotificationManager.getService();
5755 if (inm == null) {
5756 return;
5757 }
5758 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005759 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005760 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5761 } catch (RuntimeException e) {
5762 Slog.w(TAG, "Error canceling notification for service", e);
5763 } catch (RemoteException e) {
5764 }
5765
5766 }
5767
5768 private void postHeavyWeightProcessNotification(
5769 WindowProcessController proc, Intent intent, int userId) {
5770 if (proc == null) {
5771 return;
5772 }
5773
5774 final INotificationManager inm = NotificationManager.getService();
5775 if (inm == null) {
5776 return;
5777 }
5778
5779 try {
5780 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5781 String text = mContext.getString(R.string.heavy_weight_notification,
5782 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5783 Notification notification =
5784 new Notification.Builder(context,
5785 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5786 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5787 .setWhen(0)
5788 .setOngoing(true)
5789 .setTicker(text)
5790 .setColor(mContext.getColor(
5791 com.android.internal.R.color.system_notification_accent_color))
5792 .setContentTitle(text)
5793 .setContentText(
5794 mContext.getText(R.string.heavy_weight_notification_detail))
5795 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5796 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5797 new UserHandle(userId)))
5798 .build();
5799 try {
5800 inm.enqueueNotificationWithTag("android", "android", null,
5801 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5802 } catch (RuntimeException e) {
5803 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5804 } catch (RemoteException e) {
5805 }
5806 } catch (PackageManager.NameNotFoundException e) {
5807 Slog.w(TAG, "Unable to create context for heavy notification", e);
5808 }
5809
5810 }
5811
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005812 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5813 IBinder token, String resultWho, int requestCode, Intent[] intents,
5814 String[] resolvedTypes, int flags, Bundle bOptions) {
5815
5816 ActivityRecord activity = null;
5817 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5818 activity = ActivityRecord.isInStackLocked(token);
5819 if (activity == null) {
5820 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5821 return null;
5822 }
5823 if (activity.finishing) {
5824 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5825 return null;
5826 }
5827 }
5828
5829 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5830 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5831 bOptions);
5832 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5833 if (noCreate) {
5834 return rec;
5835 }
5836 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5837 if (activity.pendingResults == null) {
5838 activity.pendingResults = new HashSet<>();
5839 }
5840 activity.pendingResults.add(rec.ref);
5841 }
5842 return rec;
5843 }
5844
Andrii Kulian52d255c2018-07-13 11:32:19 -07005845 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005846 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005847 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005848 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5849 mCurAppTimeTracker.start(resumedActivity.packageName);
5850 }
5851 }
5852
5853 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5854 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005855 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005856 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5857 }
5858 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005859 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005860 constructResumedTraceName(resumed.packageName), 0);
5861 }
5862 mTracedResumedActivity = resumed;
5863 }
5864
5865 private String constructResumedTraceName(String packageName) {
5866 return "focused app: " + packageName;
5867 }
5868
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005869 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005870 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005871 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005872 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005873 // mainStack is null during startup.
5874 if (mainStack != null) {
5875 if (changes != 0 && starting == null) {
5876 // If the configuration changed, and the caller is not already
5877 // in the process of starting an activity, then find the top
5878 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005879 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005880 }
5881
5882 if (starting != null) {
5883 kept = starting.ensureActivityConfiguration(changes,
5884 false /* preserveWindow */);
5885 // And we need to make sure at this point that all other activities
5886 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005887 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005888 !PRESERVE_WINDOWS);
5889 }
5890 }
5891
5892 return kept;
5893 }
5894
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005895 void scheduleAppGcsLocked() {
5896 mH.post(() -> mAmInternal.scheduleAppGcs());
5897 }
5898
Wale Ogunwale53783742018-09-16 10:21:51 -07005899 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5900 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5901 }
5902
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005903 /**
5904 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5905 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5906 * on demand.
5907 */
5908 IPackageManager getPackageManager() {
5909 return AppGlobals.getPackageManager();
5910 }
5911
5912 PackageManagerInternal getPackageManagerInternalLocked() {
5913 if (mPmInternal == null) {
5914 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5915 }
5916 return mPmInternal;
5917 }
5918
Hai Zhangf4da9be2019-05-01 13:46:06 +08005919 PermissionPolicyInternal getPermissionPolicyInternal() {
5920 if (mPermissionPolicyInternal == null) {
5921 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5922 }
5923 return mPermissionPolicyInternal;
5924 }
5925
Wale Ogunwale008163e2018-07-23 23:11:08 -07005926 AppWarnings getAppWarningsLocked() {
5927 return mAppWarnings;
5928 }
5929
Wale Ogunwale214f3482018-10-04 11:00:47 -07005930 Intent getHomeIntent() {
5931 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5932 intent.setComponent(mTopComponent);
5933 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5934 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5935 intent.addCategory(Intent.CATEGORY_HOME);
5936 }
5937 return intent;
5938 }
5939
Chilun2ef71f72018-11-16 17:57:15 +08005940 /**
5941 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5942 * activities.
5943 *
5944 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5945 * component defined in config_secondaryHomeComponent.
5946 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5947 */
5948 Intent getSecondaryHomeIntent(String preferredPackage) {
5949 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005950 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5951 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5952 if (preferredPackage == null || useSystemProvidedLauncher) {
5953 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005954 final String secondaryHomeComponent = mContext.getResources().getString(
5955 com.android.internal.R.string.config_secondaryHomeComponent);
5956 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5957 } else {
5958 intent.setPackage(preferredPackage);
5959 }
5960 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5961 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5962 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5963 }
5964 return intent;
5965 }
5966
Wale Ogunwale214f3482018-10-04 11:00:47 -07005967 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5968 if (info == null) return null;
5969 ApplicationInfo newInfo = new ApplicationInfo(info);
5970 newInfo.initForUser(userId);
5971 return newInfo;
5972 }
5973
Wale Ogunwale9c103022018-10-18 07:44:54 -07005974 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005975 if (uid == SYSTEM_UID) {
5976 // The system gets to run in any process. If there are multiple processes with the same
5977 // uid, just pick the first (this should never happen).
5978 final SparseArray<WindowProcessController> procs =
5979 mProcessNames.getMap().get(processName);
5980 if (procs == null) return null;
5981 final int procCount = procs.size();
5982 for (int i = 0; i < procCount; i++) {
5983 final int procUid = procs.keyAt(i);
5984 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5985 // Don't use an app process or different user process for system component.
5986 continue;
5987 }
5988 return procs.valueAt(i);
5989 }
5990 }
5991
5992 return mProcessNames.get(processName, uid);
5993 }
5994
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005995 WindowProcessController getProcessController(IApplicationThread thread) {
5996 if (thread == null) {
5997 return null;
5998 }
5999
6000 final IBinder threadBinder = thread.asBinder();
6001 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6002 for (int i = pmap.size()-1; i >= 0; i--) {
6003 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6004 for (int j = procs.size() - 1; j >= 0; j--) {
6005 final WindowProcessController proc = procs.valueAt(j);
6006 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6007 return proc;
6008 }
6009 }
6010 }
6011
6012 return null;
6013 }
6014
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006015 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006016 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006017 if (proc == null) return null;
6018 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6019 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006020 }
6021 return null;
6022 }
6023
Riddle Hsua0536432019-02-16 00:38:59 +08006024 int getUidState(int uid) {
6025 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006026 }
6027
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006028 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006029 // A uid is considered to be foreground if it has a visible non-toast window.
6030 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006031 }
6032
Ricky Wai96f5c352019-04-10 18:40:17 +01006033 boolean isDeviceOwner(int uid) {
6034 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006035 }
6036
Ricky Wai96f5c352019-04-10 18:40:17 +01006037 void setDeviceOwnerUid(int uid) {
6038 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006039 }
6040
Wale Ogunwale9de19442018-10-18 19:05:03 -07006041 /**
6042 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6043 * the whitelist
6044 */
6045 String getPendingTempWhitelistTagForUidLocked(int uid) {
6046 return mPendingTempWhitelist.get(uid);
6047 }
6048
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006049 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6050 if (true || Build.IS_USER) {
6051 return;
6052 }
6053
6054 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6055 StrictMode.allowThreadDiskWrites();
6056 try {
6057 File tracesDir = new File("/data/anr");
6058 File tracesFile = null;
6059 try {
6060 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6061
6062 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006063 String timeString =
6064 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6065 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006066 sb.append(": ");
6067 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6068 sb.append(" since ");
6069 sb.append(msg);
6070 FileOutputStream fos = new FileOutputStream(tracesFile);
6071 fos.write(sb.toString().getBytes());
6072 if (app == null) {
6073 fos.write("\n*** No application process!".getBytes());
6074 }
6075 fos.close();
6076 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6077 } catch (IOException e) {
6078 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6079 return;
6080 }
6081
6082 if (app != null && app.getPid() > 0) {
6083 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6084 firstPids.add(app.getPid());
6085 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6086 }
6087
6088 File lastTracesFile = null;
6089 File curTracesFile = null;
6090 for (int i=9; i>=0; i--) {
6091 String name = String.format(Locale.US, "slow%02d.txt", i);
6092 curTracesFile = new File(tracesDir, name);
6093 if (curTracesFile.exists()) {
6094 if (lastTracesFile != null) {
6095 curTracesFile.renameTo(lastTracesFile);
6096 } else {
6097 curTracesFile.delete();
6098 }
6099 }
6100 lastTracesFile = curTracesFile;
6101 }
6102 tracesFile.renameTo(curTracesFile);
6103 } finally {
6104 StrictMode.setThreadPolicy(oldPolicy);
6105 }
6106 }
6107
Michal Karpinskida34cd42019-04-02 19:46:52 +01006108 boolean isAssociatedCompanionApp(int userId, int uid) {
6109 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6110 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006111 return false;
6112 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006113 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006114 }
6115
Issei Suzuki734bc942019-06-05 13:59:52 +02006116 void notifySingleTaskDisplayEmpty(int displayId) {
6117 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6118 }
6119
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006120 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006121 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006122
6123
Wale Ogunwale98875612018-10-12 07:53:02 -07006124 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6125 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006126
Riddle Hsud93a6c42018-11-29 21:50:06 +08006127 H(Looper looper) {
6128 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006129 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006130
6131 @Override
6132 public void handleMessage(Message msg) {
6133 switch (msg.what) {
6134 case REPORT_TIME_TRACKER_MSG: {
6135 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6136 tracker.deliverResult(mContext);
6137 } break;
6138 }
6139 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006140 }
6141
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006142 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006143 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006144
6145 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006146 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006147 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006148
6149 @Override
6150 public void handleMessage(Message msg) {
6151 switch (msg.what) {
6152 case DISMISS_DIALOG_UI_MSG: {
6153 final Dialog d = (Dialog) msg.obj;
6154 d.dismiss();
6155 break;
6156 }
6157 }
6158 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006159 }
6160
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 final class LocalService extends ActivityTaskManagerInternal {
6162 @Override
6163 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006164 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006165 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167
6168 @Override
6169 public ComponentName getHomeActivityForUser(int userId) {
6170 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006171 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006172 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006173 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175 }
6176
6177 @Override
6178 public void onLocalVoiceInteractionStarted(IBinder activity,
6179 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6180 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006181 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 }
6183 }
6184
6185 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006186 public void notifySingleTaskDisplayDrawn(int displayId) {
6187 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6188 }
6189
6190 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 public void notifyAppTransitionFinished() {
6192 synchronized (mGlobalLock) {
6193 mStackSupervisor.notifyAppTransitionDone();
6194 }
6195 }
6196
6197 @Override
6198 public void notifyAppTransitionCancelled() {
6199 synchronized (mGlobalLock) {
6200 mStackSupervisor.notifyAppTransitionDone();
6201 }
6202 }
6203
6204 @Override
6205 public List<IBinder> getTopVisibleActivities() {
6206 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006207 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 }
6209 }
6210
6211 @Override
6212 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6213 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006214 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006215 }
6216 }
6217
6218 @Override
6219 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6220 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006221 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 final String[] resolvedTypes = new String[intents.length];
6223
6224 // UID of the package on user userId.
6225 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6226 // packageUid may not be initialized.
6227 int packageUid = 0;
6228 final long ident = Binder.clearCallingIdentity();
6229
6230 try {
6231 for (int i = 0; i < intents.length; i++) {
6232 resolvedTypes[i] =
6233 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6234 }
6235
6236 packageUid = AppGlobals.getPackageManager().getPackageUid(
6237 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6238 } catch (RemoteException e) {
6239 // Shouldn't happen.
6240 } finally {
6241 Binder.restoreCallingIdentity(ident);
6242 }
6243
Riddle Hsu591bf612019-02-14 17:55:31 +08006244 return getActivityStartController().startActivitiesInPackage(
6245 packageUid, packageName,
6246 intents, resolvedTypes, null /* resultTo */,
6247 SafeActivityOptions.fromBundle(bOptions), userId,
6248 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6249 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 }
6251
6252 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006253 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6254 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6255 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6256 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006257 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006258 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006259 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6260 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6261 userId, validateIncomingUser, originatingPendingIntent,
6262 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006263 }
6264 }
6265
6266 @Override
6267 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6268 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6269 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006270 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006271 PendingIntentRecord originatingPendingIntent,
6272 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006273 synchronized (mGlobalLock) {
6274 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6275 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6276 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006277 validateIncomingUser, originatingPendingIntent,
6278 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006279 }
6280 }
6281
6282 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6284 Intent intent, Bundle options, int userId) {
6285 return ActivityTaskManagerService.this.startActivityAsUser(
6286 caller, callerPacakge, intent,
6287 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6288 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6289 false /*validateIncomingUser*/);
6290 }
6291
6292 @Override
lumark588a3e82018-07-20 18:53:54 +08006293 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 synchronized (mGlobalLock) {
6295
6296 // We might change the visibilities here, so prepare an empty app transition which
6297 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006298 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006299 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006300 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006301 return;
6302 }
Louis Chang677921f2019-12-06 16:44:24 +08006303 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006304 final boolean wasTransitionSet =
6305 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006307 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006308 }
Louis Chang149d5c82019-12-30 09:47:39 +08006309 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310
6311 // If there was a transition set already we don't want to interfere with it as we
6312 // might be starting it too early.
6313 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006314 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
6316 }
6317 if (callback != null) {
6318 callback.run();
6319 }
6320 }
6321
6322 @Override
6323 public void notifyKeyguardTrustedChanged() {
6324 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006325 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006326 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006327 }
6328 }
6329 }
6330
6331 /**
6332 * Called after virtual display Id is updated by
6333 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6334 * {@param vrVr2dDisplayId}.
6335 */
6336 @Override
6337 public void setVr2dDisplayId(int vr2dDisplayId) {
6338 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6339 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006340 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006341 }
6342 }
6343
6344 @Override
6345 public void setFocusedActivity(IBinder token) {
6346 synchronized (mGlobalLock) {
6347 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6348 if (r == null) {
6349 throw new IllegalArgumentException(
6350 "setFocusedActivity: No activity record matching token=" + token);
6351 }
Louis Chang19443452018-10-09 12:10:21 +08006352 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006353 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006354 }
6355 }
6356 }
6357
6358 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006359 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006360 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006361 }
6362
6363 @Override
6364 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006365 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006366 }
6367
6368 @Override
6369 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006370 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006371 }
6372
6373 @Override
6374 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6375 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6376 }
6377
6378 @Override
6379 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006380 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006381 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006382
6383 @Override
6384 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6385 synchronized (mGlobalLock) {
6386 mActiveVoiceInteractionServiceComponent = component;
6387 }
6388 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006389
6390 @Override
6391 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6392 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6393 return;
6394 }
6395 synchronized (mGlobalLock) {
6396 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6397 if (types == null) {
6398 if (uid < 0) {
6399 return;
6400 }
6401 types = new ArrayMap<>();
6402 mAllowAppSwitchUids.put(userId, types);
6403 }
6404 if (uid < 0) {
6405 types.remove(type);
6406 } else {
6407 types.put(type, uid);
6408 }
6409 }
6410 }
6411
6412 @Override
6413 public void onUserStopped(int userId) {
6414 synchronized (mGlobalLock) {
6415 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6416 mAllowAppSwitchUids.remove(userId);
6417 }
6418 }
6419
6420 @Override
6421 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6422 synchronized (mGlobalLock) {
6423 return ActivityTaskManagerService.this.isGetTasksAllowed(
6424 caller, callingPid, callingUid);
6425 }
6426 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006427
Riddle Hsua0536432019-02-16 00:38:59 +08006428 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006429 @Override
6430 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006431 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006432 mProcessNames.put(proc.mName, proc.mUid, proc);
6433 }
6434 }
6435
Riddle Hsua0536432019-02-16 00:38:59 +08006436 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006437 @Override
6438 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006439 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006440 mProcessNames.remove(name, uid);
6441 }
6442 }
6443
Riddle Hsua0536432019-02-16 00:38:59 +08006444 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006445 @Override
6446 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006447 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006448 if (proc == mHomeProcess) {
6449 mHomeProcess = null;
6450 }
6451 if (proc == mPreviousProcess) {
6452 mPreviousProcess = null;
6453 }
6454 }
6455 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006456
Riddle Hsua0536432019-02-16 00:38:59 +08006457 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006458 @Override
6459 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006460 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006461 return mTopProcessState;
6462 }
6463 }
6464
Riddle Hsua0536432019-02-16 00:38:59 +08006465 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006466 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006467 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006468 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006469 return proc == mHeavyWeightProcess;
6470 }
6471 }
6472
Riddle Hsua0536432019-02-16 00:38:59 +08006473 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006474 @Override
6475 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006476 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006477 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6478 }
6479 }
6480
6481 @Override
6482 public void finishHeavyWeightApp() {
6483 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006484 if (mHeavyWeightProcess != null) {
6485 mHeavyWeightProcess.finishActivities();
6486 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006487 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6488 mHeavyWeightProcess);
6489 }
6490 }
6491
Riddle Hsua0536432019-02-16 00:38:59 +08006492 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006493 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006494 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006495 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006496 return isSleepingLocked();
6497 }
6498 }
6499
6500 @Override
6501 public boolean isShuttingDown() {
6502 synchronized (mGlobalLock) {
6503 return mShuttingDown;
6504 }
6505 }
6506
6507 @Override
6508 public boolean shuttingDown(boolean booted, int timeout) {
6509 synchronized (mGlobalLock) {
6510 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006511 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006512 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006513 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006514 return mStackSupervisor.shutdownLocked(timeout);
6515 }
6516 }
6517
6518 @Override
6519 public void enableScreenAfterBoot(boolean booted) {
6520 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006521 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006522 mWindowManager.enableScreenAfterBoot();
6523 updateEventDispatchingLocked(booted);
6524 }
6525 }
6526
6527 @Override
6528 public boolean showStrictModeViolationDialog() {
6529 synchronized (mGlobalLock) {
6530 return mShowDialogs && !mSleeping && !mShuttingDown;
6531 }
6532 }
6533
6534 @Override
6535 public void showSystemReadyErrorDialogsIfNeeded() {
6536 synchronized (mGlobalLock) {
6537 try {
6538 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6539 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6540 + " data partition or your device will be unstable.");
6541 mUiHandler.post(() -> {
6542 if (mShowDialogs) {
6543 AlertDialog d = new BaseErrorDialog(mUiContext);
6544 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6545 d.setCancelable(false);
6546 d.setTitle(mUiContext.getText(R.string.android_system_label));
6547 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6548 d.setButton(DialogInterface.BUTTON_POSITIVE,
6549 mUiContext.getText(R.string.ok),
6550 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6551 d.show();
6552 }
6553 });
6554 }
6555 } catch (RemoteException e) {
6556 }
6557
6558 if (!Build.isBuildConsistent()) {
6559 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6560 mUiHandler.post(() -> {
6561 if (mShowDialogs) {
6562 AlertDialog d = new BaseErrorDialog(mUiContext);
6563 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6564 d.setCancelable(false);
6565 d.setTitle(mUiContext.getText(R.string.android_system_label));
6566 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6567 d.setButton(DialogInterface.BUTTON_POSITIVE,
6568 mUiContext.getText(R.string.ok),
6569 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6570 d.show();
6571 }
6572 });
6573 }
6574 }
6575 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006576
6577 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006578 public void onProcessMapped(int pid, WindowProcessController proc) {
6579 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006580 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006581 }
6582 }
6583
6584 @Override
6585 public void onProcessUnMapped(int pid) {
6586 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006587 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006588 }
6589 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006590
6591 @Override
6592 public void onPackageDataCleared(String name) {
6593 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006594 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006595 mAppWarnings.onPackageDataCleared(name);
6596 }
6597 }
6598
6599 @Override
6600 public void onPackageUninstalled(String name) {
6601 synchronized (mGlobalLock) {
6602 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006603 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006604 }
6605 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006606
6607 @Override
6608 public void onPackageAdded(String name, boolean replacing) {
6609 synchronized (mGlobalLock) {
6610 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6611 }
6612 }
6613
6614 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006615 public void onPackageReplaced(ApplicationInfo aInfo) {
6616 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006617 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006618 }
6619 }
6620
6621 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006622 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6623 synchronized (mGlobalLock) {
6624 return compatibilityInfoForPackageLocked(ai);
6625 }
6626 }
6627
Yunfan Chen75157d72018-07-27 14:47:21 +09006628 /**
6629 * Set the corresponding display information for the process global configuration. To be
6630 * called when we need to show IME on a different display.
6631 *
6632 * @param pid The process id associated with the IME window.
6633 * @param displayId The ID of the display showing the IME.
6634 */
6635 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006636 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006637 // Don't update process-level configuration for Multi-Client IME process since other
6638 // IMEs on other displays will also receive this configuration change due to IME
6639 // services use the same application config/context.
6640 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006641
Yunfan Chen75157d72018-07-27 14:47:21 +09006642 if (pid == MY_PID || pid < 0) {
6643 if (DEBUG_CONFIGURATION) {
6644 Slog.w(TAG,
6645 "Trying to update display configuration for system/invalid process.");
6646 }
6647 return;
6648 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006649 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006650 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006651 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006652 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006653 // Call might come when display is not yet added or has been removed.
6654 if (DEBUG_CONFIGURATION) {
6655 Slog.w(TAG, "Trying to update display configuration for non-existing "
6656 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006657 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006658 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006659 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006660 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006661 if (process == null) {
6662 if (DEBUG_CONFIGURATION) {
6663 Slog.w(TAG, "Trying to update display configuration for invalid "
6664 + "process, pid=" + pid);
6665 }
6666 return;
6667 }
lumarkddc77fb2019-06-27 22:22:23 +08006668 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006669 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006670 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006671 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006672
6673 @Override
6674 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006675 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006676 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006677 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6678 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006679 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006680 }
6681 }
6682 }
6683
6684 @Override
6685 public void clearPendingResultForActivity(IBinder activityToken,
6686 WeakReference<PendingIntentRecord> pir) {
6687 synchronized (mGlobalLock) {
6688 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6689 if (r != null && r.pendingResults != null) {
6690 r.pendingResults.remove(pir);
6691 }
6692 }
6693 }
6694
6695 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006696 public ActivityTokens getTopActivityForTask(int taskId) {
6697 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006698 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006699 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006700 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6701 + " Requested task not found");
6702 return null;
6703 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006704 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006705 if (activity == null) {
6706 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6707 + " Requested activity not found");
6708 return null;
6709 }
6710 if (!activity.attachedToProcess()) {
6711 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6712 + activity);
6713 return null;
6714 }
6715 return new ActivityTokens(activity.appToken, activity.assistToken,
6716 activity.app.getThread());
6717 }
6718 }
6719
6720 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006721 public IIntentSender getIntentSender(int type, String packageName,
6722 int callingUid, int userId, IBinder token, String resultWho,
6723 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6724 Bundle bOptions) {
6725 synchronized (mGlobalLock) {
6726 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6727 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6728 }
6729 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006730
6731 @Override
6732 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6733 synchronized (mGlobalLock) {
6734 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6735 if (r == null) {
6736 return null;
6737 }
6738 if (r.mServiceConnectionsHolder == null) {
6739 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6740 ActivityTaskManagerService.this, r);
6741 }
6742
6743 return r.mServiceConnectionsHolder;
6744 }
6745 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006746
6747 @Override
6748 public Intent getHomeIntent() {
6749 synchronized (mGlobalLock) {
6750 return ActivityTaskManagerService.this.getHomeIntent();
6751 }
6752 }
6753
6754 @Override
6755 public boolean startHomeActivity(int userId, String reason) {
6756 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006757 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006758 }
6759 }
6760
6761 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006762 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006763 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006764 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006765 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006766 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006767 }
Chilun8b1f1be2019-03-13 17:14:36 +08006768 }
6769
6770 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006771 public boolean startHomeOnAllDisplays(int userId, String reason) {
6772 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006773 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006774 }
6775 }
6776
Riddle Hsua0536432019-02-16 00:38:59 +08006777 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006778 @Override
6779 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006780 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006781 if (mFactoryTest == FACTORY_TEST_OFF) {
6782 return false;
6783 }
6784 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6785 && wpc.mName.equals(mTopComponent.getPackageName())) {
6786 return true;
6787 }
6788 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6789 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6790 }
6791 }
6792
6793 @Override
6794 public void updateTopComponentForFactoryTest() {
6795 synchronized (mGlobalLock) {
6796 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6797 return;
6798 }
6799 final ResolveInfo ri = mContext.getPackageManager()
6800 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6801 final CharSequence errorMsg;
6802 if (ri != null) {
6803 final ActivityInfo ai = ri.activityInfo;
6804 final ApplicationInfo app = ai.applicationInfo;
6805 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6806 mTopAction = Intent.ACTION_FACTORY_TEST;
6807 mTopData = null;
6808 mTopComponent = new ComponentName(app.packageName, ai.name);
6809 errorMsg = null;
6810 } else {
6811 errorMsg = mContext.getResources().getText(
6812 com.android.internal.R.string.factorytest_not_system);
6813 }
6814 } else {
6815 errorMsg = mContext.getResources().getText(
6816 com.android.internal.R.string.factorytest_no_action);
6817 }
6818 if (errorMsg == null) {
6819 return;
6820 }
6821
6822 mTopAction = null;
6823 mTopData = null;
6824 mTopComponent = null;
6825 mUiHandler.post(() -> {
6826 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6827 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006828 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006829 });
6830 }
6831 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832
Riddle Hsua0536432019-02-16 00:38:59 +08006833 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 @Override
6835 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6836 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006837 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006839 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840
6841 wpc.clearRecentTasks();
6842 wpc.clearActivities();
6843
6844 if (wpc.isInstrumenting()) {
6845 finishInstrumentationCallback.run();
6846 }
6847
Jorim Jaggid0752812018-10-16 16:07:20 +02006848 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006849 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006850 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006851 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006852 // If there was nothing to resume, and we are not already restarting
6853 // this process, but there is a visible activity that is hosted by the
6854 // process...then make sure all visible activities are running, taking
6855 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006856 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006857 !PRESERVE_WINDOWS);
6858 }
6859 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006860 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 }
6863 }
6864 }
6865
6866 @Override
6867 public void closeSystemDialogs(String reason) {
6868 enforceNotIsolatedCaller("closeSystemDialogs");
6869
6870 final int pid = Binder.getCallingPid();
6871 final int uid = Binder.getCallingUid();
6872 final long origId = Binder.clearCallingIdentity();
6873 try {
6874 synchronized (mGlobalLock) {
6875 // Only allow this from foreground processes, so that background
6876 // applications can't abuse it to prevent system UI from being shown.
6877 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006878 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 if (!proc.isPerceptible()) {
6880 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6881 + " from background process " + proc);
6882 return;
6883 }
6884 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 mWindowManager.closeSystemDialogs(reason);
6886
Louis Chang149d5c82019-12-30 09:47:39 +08006887 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006889 // Call into AM outside the synchronized block.
6890 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006891 } finally {
6892 Binder.restoreCallingIdentity(origId);
6893 }
6894 }
6895
6896 @Override
6897 public void cleanupDisabledPackageComponents(
6898 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6899 synchronized (mGlobalLock) {
6900 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006901 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006903 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006904 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 }
6906
6907 // Clean-up disabled tasks
6908 getRecentTasks().cleanupDisabledPackageTasksLocked(
6909 packageName, disabledClasses, userId);
6910 }
6911 }
6912
6913 @Override
6914 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6915 int userId) {
6916 synchronized (mGlobalLock) {
6917
6918 boolean didSomething =
6919 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006920 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006921 null, doit, evenPersistent, userId);
6922 return didSomething;
6923 }
6924 }
6925
6926 @Override
6927 public void resumeTopActivities(boolean scheduleIdle) {
6928 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006929 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006931 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006932 }
6933 }
6934 }
6935
Riddle Hsua0536432019-02-16 00:38:59 +08006936 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 @Override
6938 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006939 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6941 }
6942 }
6943
Riddle Hsua0536432019-02-16 00:38:59 +08006944 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006945 @Override
6946 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006947 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006948 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6949 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6950 }
6951 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006952 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006953 } finally {
6954 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6955 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 }
6957 }
6958
6959 @Override
6960 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6961 try {
6962 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6963 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6964 }
6965 } catch (RemoteException ex) {
6966 throw new SecurityException("Fail to check is caller a privileged app", ex);
6967 }
6968
6969 synchronized (mGlobalLock) {
6970 final long ident = Binder.clearCallingIdentity();
6971 try {
6972 if (mAmInternal.shouldConfirmCredentials(userId)) {
6973 if (mKeyguardController.isKeyguardLocked()) {
6974 // Showing launcher to avoid user entering credential twice.
6975 startHomeActivity(currentUserId, "notifyLockedProfile");
6976 }
Louis Chang149d5c82019-12-30 09:47:39 +08006977 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 }
6979 } finally {
6980 Binder.restoreCallingIdentity(ident);
6981 }
6982 }
6983 }
6984
6985 @Override
6986 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6987 mAmInternal.enforceCallingPermission(
6988 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6989
6990 synchronized (mGlobalLock) {
6991 final long ident = Binder.clearCallingIdentity();
6992 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006993 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6994 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006996 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6997 UserHandle.CURRENT);
6998 } finally {
6999 Binder.restoreCallingIdentity(ident);
7000 }
7001 }
7002 }
7003
7004 @Override
7005 public void writeActivitiesToProto(ProtoOutputStream proto) {
7006 synchronized (mGlobalLock) {
7007 // The output proto of "activity --proto activities"
7008 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007009 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007010 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7011 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007012 }
7013 }
7014
7015 @Override
7016 public void saveANRState(String reason) {
7017 synchronized (mGlobalLock) {
7018 final StringWriter sw = new StringWriter();
7019 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7020 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7021 if (reason != null) {
7022 pw.println(" Reason: " + reason);
7023 }
7024 pw.println();
7025 getActivityStartController().dump(pw, " ", null);
7026 pw.println();
7027 pw.println("-------------------------------------------------------------------------------");
7028 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7029 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7030 "" /* header */);
7031 pw.println();
7032 pw.close();
7033
7034 mLastANRState = sw.toString();
7035 }
7036 }
7037
7038 @Override
7039 public void clearSavedANRState() {
7040 synchronized (mGlobalLock) {
7041 mLastANRState = null;
7042 }
7043 }
7044
7045 @Override
7046 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7047 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7048 synchronized (mGlobalLock) {
7049 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7050 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7051 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7052 dumpLastANRLocked(pw);
7053 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7054 dumpLastANRTracesLocked(pw);
7055 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7056 dumpActivityStarterLocked(pw, dumpPackage);
7057 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7058 dumpActivityContainersLocked(pw);
7059 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7060 if (getRecentTasks() != null) {
7061 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7062 }
7063 }
7064 }
7065 }
7066
7067 @Override
7068 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7069 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7070 int wakefulness) {
7071 synchronized (mGlobalLock) {
7072 if (mHomeProcess != null && (dumpPackage == null
7073 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7074 if (needSep) {
7075 pw.println();
7076 needSep = false;
7077 }
7078 pw.println(" mHomeProcess: " + mHomeProcess);
7079 }
7080 if (mPreviousProcess != null && (dumpPackage == null
7081 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7082 if (needSep) {
7083 pw.println();
7084 needSep = false;
7085 }
7086 pw.println(" mPreviousProcess: " + mPreviousProcess);
7087 }
7088 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7089 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7090 StringBuilder sb = new StringBuilder(128);
7091 sb.append(" mPreviousProcessVisibleTime: ");
7092 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7093 pw.println(sb);
7094 }
7095 if (mHeavyWeightProcess != null && (dumpPackage == null
7096 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7097 if (needSep) {
7098 pw.println();
7099 needSep = false;
7100 }
7101 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7102 }
7103 if (dumpPackage == null) {
7104 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007105 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 }
7107 if (dumpAll) {
7108 if (dumpPackage == null) {
7109 pw.println(" mConfigWillChange: "
7110 + getTopDisplayFocusedStack().mConfigWillChange);
7111 }
7112 if (mCompatModePackages.getPackages().size() > 0) {
7113 boolean printed = false;
7114 for (Map.Entry<String, Integer> entry
7115 : mCompatModePackages.getPackages().entrySet()) {
7116 String pkg = entry.getKey();
7117 int mode = entry.getValue();
7118 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7119 continue;
7120 }
7121 if (!printed) {
7122 pw.println(" mScreenCompatPackages:");
7123 printed = true;
7124 }
7125 pw.println(" " + pkg + ": " + mode);
7126 }
7127 }
7128 }
7129
7130 if (dumpPackage == null) {
7131 pw.println(" mWakefulness="
7132 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007133 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 if (mRunningVoice != null) {
7135 pw.println(" mRunningVoice=" + mRunningVoice);
7136 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7137 }
7138 pw.println(" mSleeping=" + mSleeping);
7139 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7140 pw.println(" mVrController=" + mVrController);
7141 }
7142 if (mCurAppTimeTracker != null) {
7143 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7144 }
7145 if (mAllowAppSwitchUids.size() > 0) {
7146 boolean printed = false;
7147 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7148 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7149 for (int j = 0; j < types.size(); j++) {
7150 if (dumpPackage == null ||
7151 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7152 if (needSep) {
7153 pw.println();
7154 needSep = false;
7155 }
7156 if (!printed) {
7157 pw.println(" mAllowAppSwitchUids:");
7158 printed = true;
7159 }
7160 pw.print(" User ");
7161 pw.print(mAllowAppSwitchUids.keyAt(i));
7162 pw.print(": Type ");
7163 pw.print(types.keyAt(j));
7164 pw.print(" = ");
7165 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7166 pw.println();
7167 }
7168 }
7169 }
7170 }
7171 if (dumpPackage == null) {
7172 if (mController != null) {
7173 pw.println(" mController=" + mController
7174 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7175 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007176 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7177 pw.println(" mLaunchingActivityWakeLock="
7178 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 }
7180
7181 return needSep;
7182 }
7183 }
7184
7185 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007186 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7187 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 synchronized (mGlobalLock) {
7189 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007190 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007192 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7193 if (mRunningVoice != null) {
7194 final long vrToken = proto.start(
7195 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7196 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7197 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007198 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007199 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7200 proto.end(vrToken);
7201 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007202 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007203 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 if (mController != null) {
7205 final long token = proto.start(CONTROLLER);
7206 proto.write(CONTROLLER, mController.toString());
7207 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7208 proto.end(token);
7209 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007210 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7211 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007212 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007213 }
7214
7215 if (mHomeProcess != null && (dumpPackage == null
7216 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007217 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007218 }
7219
7220 if (mPreviousProcess != null && (dumpPackage == null
7221 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007222 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7224 }
7225
7226 if (mHeavyWeightProcess != null && (dumpPackage == null
7227 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007228 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 }
7230
7231 for (Map.Entry<String, Integer> entry
7232 : mCompatModePackages.getPackages().entrySet()) {
7233 String pkg = entry.getKey();
7234 int mode = entry.getValue();
7235 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7236 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7237 proto.write(PACKAGE, pkg);
7238 proto.write(MODE, mode);
7239 proto.end(compatToken);
7240 }
7241 }
7242
7243 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007244 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007245 }
7246
7247 }
7248 }
7249
7250 @Override
7251 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7252 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7253 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007254 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7255 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007256 }
7257
7258 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007259 public void dumpForOom(PrintWriter pw) {
7260 synchronized (mGlobalLock) {
7261 pw.println(" mHomeProcess: " + mHomeProcess);
7262 pw.println(" mPreviousProcess: " + mPreviousProcess);
7263 if (mHeavyWeightProcess != null) {
7264 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7265 }
7266 }
7267 }
7268
7269 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007270 public boolean canGcNow() {
7271 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007272 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007273 }
7274 }
7275
Riddle Hsua0536432019-02-16 00:38:59 +08007276 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007277 @Override
7278 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007279 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007280 if (mRootWindowContainer == null) {
7281 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007282 // oomadj after AMS created.
7283 return null;
7284 }
Louis Chang149d5c82019-12-30 09:47:39 +08007285 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007286 return top != null ? top.app : null;
7287 }
7288 }
7289
Riddle Hsua0536432019-02-16 00:38:59 +08007290 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 @Override
7292 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007293 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007294 if (mRootWindowContainer != null) {
7295 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007296 }
7297 }
7298 }
7299
7300 @Override
7301 public void scheduleDestroyAllActivities(String reason) {
7302 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007303 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007304 }
7305 }
7306
7307 @Override
7308 public void removeUser(int userId) {
7309 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007310 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007311 }
7312 }
7313
7314 @Override
7315 public boolean switchUser(int userId, UserState userState) {
7316 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007317 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007318 }
7319 }
7320
7321 @Override
7322 public void onHandleAppCrash(WindowProcessController wpc) {
7323 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007324 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007325 }
7326 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007327
7328 @Override
7329 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7330 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007331 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007332 }
7333 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007334
Riddle Hsua0536432019-02-16 00:38:59 +08007335 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007336 @Override
7337 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007338 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007339 }
7340
Riddle Hsua0536432019-02-16 00:38:59 +08007341 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007342 @Override
7343 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007344 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007345 }
7346
Riddle Hsua0536432019-02-16 00:38:59 +08007347 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007348 @Override
7349 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007350 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007351 }
7352
Riddle Hsua0536432019-02-16 00:38:59 +08007353 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007354 @Override
7355 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007356 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007357 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007358
7359 @Override
7360 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007361 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007362 mPendingTempWhitelist.put(uid, tag);
7363 }
7364 }
7365
7366 @Override
7367 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007368 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007369 mPendingTempWhitelist.remove(uid);
7370 }
7371 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007372
7373 @Override
7374 public boolean handleAppCrashInActivityController(String processName, int pid,
7375 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7376 Runnable killCrashingAppCallback) {
7377 synchronized (mGlobalLock) {
7378 if (mController == null) {
7379 return false;
7380 }
7381
7382 try {
7383 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7384 stackTrace)) {
7385 killCrashingAppCallback.run();
7386 return true;
7387 }
7388 } catch (RemoteException e) {
7389 mController = null;
7390 Watchdog.getInstance().setActivityController(null);
7391 }
7392 return false;
7393 }
7394 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007395
7396 @Override
7397 public void removeRecentTasksByPackageName(String packageName, int userId) {
7398 synchronized (mGlobalLock) {
7399 mRecentTasks.removeTasksByPackageName(packageName, userId);
7400 }
7401 }
7402
7403 @Override
7404 public void cleanupRecentTasksForUser(int userId) {
7405 synchronized (mGlobalLock) {
7406 mRecentTasks.cleanupLocked(userId);
7407 }
7408 }
7409
7410 @Override
7411 public void loadRecentTasksForUser(int userId) {
7412 synchronized (mGlobalLock) {
7413 mRecentTasks.loadUserRecentsLocked(userId);
7414 }
7415 }
7416
7417 @Override
7418 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7419 synchronized (mGlobalLock) {
7420 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7421 }
7422 }
7423
7424 @Override
7425 public void flushRecentTasks() {
7426 mRecentTasks.flush();
7427 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007428
7429 @Override
7430 public WindowProcessController getHomeProcess() {
7431 synchronized (mGlobalLock) {
7432 return mHomeProcess;
7433 }
7434 }
7435
7436 @Override
7437 public WindowProcessController getPreviousProcess() {
7438 synchronized (mGlobalLock) {
7439 return mPreviousProcess;
7440 }
7441 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007442
7443 @Override
7444 public void clearLockedTasks(String reason) {
7445 synchronized (mGlobalLock) {
7446 getLockTaskController().clearLockedTasks(reason);
7447 }
7448 }
7449
7450 @Override
7451 public void updateUserConfiguration() {
7452 synchronized (mGlobalLock) {
7453 final Configuration configuration = new Configuration(getGlobalConfiguration());
7454 final int currentUserId = mAmInternal.getCurrentUserId();
7455 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7456 configuration, currentUserId, Settings.System.canWrite(mContext));
7457 updateConfigurationLocked(configuration, null /* starting */,
7458 false /* initLocale */, false /* persistent */, currentUserId,
7459 false /* deferResume */);
7460 }
7461 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007462
7463 @Override
7464 public boolean canShowErrorDialogs() {
7465 synchronized (mGlobalLock) {
7466 return mShowDialogs && !mSleeping && !mShuttingDown
7467 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7468 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7469 mAmInternal.getCurrentUserId())
7470 && !(UserManager.isDeviceInDemoMode(mContext)
7471 && mAmInternal.getCurrentUser().isDemo());
7472 }
7473 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007474
7475 @Override
7476 public void setProfileApp(String profileApp) {
7477 synchronized (mGlobalLock) {
7478 mProfileApp = profileApp;
7479 }
7480 }
7481
7482 @Override
7483 public void setProfileProc(WindowProcessController wpc) {
7484 synchronized (mGlobalLock) {
7485 mProfileProc = wpc;
7486 }
7487 }
7488
7489 @Override
7490 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7491 synchronized (mGlobalLock) {
7492 mProfilerInfo = profilerInfo;
7493 }
7494 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007495
7496 @Override
7497 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7498 synchronized (mGlobalLock) {
7499 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7500 }
7501 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007502
7503 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007504 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7505 boolean reducedResolution) {
7506 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7507 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007508 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007509
7510 @Override
7511 public boolean isUidForeground(int uid) {
7512 synchronized (mGlobalLock) {
7513 return ActivityTaskManagerService.this.isUidForeground(uid);
7514 }
7515 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007516
7517 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007518 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007519 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007520 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007521 }
7522 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007523
7524 @Override
7525 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007526 // Translate package names into UIDs
7527 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007528 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007529 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7530 if (uid >= 0) {
7531 result.add(uid);
7532 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007533 }
7534 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007535 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007536 }
7537 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007538 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007539}