blob: ac1dbc4b755a2795a2763bf4186c75b683ee4ce0 [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;
299import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300
301/**
302 * System service for managing activities and their containers (task, stacks, displays,... ).
303 *
304 * {@hide}
305 */
306public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000309 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700310 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
311 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
312 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
313 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700314 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700315
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100320 // How long we permit background activity starts after an activity in the process
321 // started or finished.
322 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700323
Wale Ogunwale98875612018-10-12 07:53:02 -0700324 /** Used to indicate that an app transition should be animated. */
325 static final boolean ANIMATE = true;
326
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700327 /** Hardware-reported OpenGLES version. */
328 final int GL_ES_VERSION;
329
Wale Ogunwale31913b52018-10-13 08:29:31 -0700330 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
331 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
332 public static final String DUMP_LASTANR_CMD = "lastanr" ;
333 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
334 public static final String DUMP_STARTER_CMD = "starter" ;
335 public static final String DUMP_CONTAINERS_CMD = "containers" ;
336 public static final String DUMP_RECENTS_CMD = "recents" ;
337 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
338
Wale Ogunwale64258362018-10-16 15:13:37 -0700339 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
340 public static final int RELAUNCH_REASON_NONE = 0;
341 /** This activity is being relaunched due to windowing mode change. */
342 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
343 /** This activity is being relaunched due to a free-resize operation. */
344 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
345
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700346 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700347
Wale Ogunwalef6733932018-06-27 05:14:34 -0700348 /**
349 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
350 * change at runtime. Use mContext for non-UI purposes.
351 */
352 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700358 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800359 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800360 @VisibleForTesting
361 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 PowerManagerInternal mPowerManagerInternal;
363 private UsageStatsManagerInternal mUsageStatsInternal;
364
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700365 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 IntentFirewall mIntentFirewall;
367
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700368 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800369 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700371 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
373 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
374 *
375 * @see WindowManagerThreadPriorityBooster
376 */
377 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800379 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700380 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700381 private UserManagerService mUserManager;
382 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700383 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800384 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700385 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** All processes currently running that might have a window organized by name. */
387 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100388 /** All processes we currently have running mapped by pid and uid */
389 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /** This is the process holding what we currently consider to be the "home" activity. */
391 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700392 /** The currently running heavy-weight process, if any. */
393 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700394 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700395 /**
396 * This is the process holding the activity the user last visited that is in a different process
397 * from the one they are currently in.
398 */
399 WindowProcessController mPreviousProcess;
400 /** The time at which the previous process was last visible. */
401 long mPreviousProcessVisibleTime;
402
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700403 /** List of intents that were used to start the most recent tasks. */
404 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700405 /** State of external calls telling us if the device is awake or asleep. */
406 private boolean mKeyguardShown = false;
407
408 // Wrapper around VoiceInteractionServiceManager
409 private AssistUtils mAssistUtils;
410
411 // VoiceInteraction session ID that changes for each new request except when
412 // being called for multi-window assist in a single session.
413 private int mViSessionId = 1000;
414
415 // How long to wait in getAssistContextExtras for the activity and foreground services
416 // to respond with the result.
417 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
418
419 // How long top wait when going through the modern assist (which doesn't need to block
420 // on getting this result before starting to launch its UI).
421 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
422
423 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
424 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
425
Alison Cichowlas3e340502018-08-07 17:15:01 -0400426 // Permission tokens are used to temporarily granted a trusted app the ability to call
427 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
428 // showing any appropriate error messages to the user.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
430 10 * MINUTE_IN_MILLIS;
431
432 // How long before the service actually expires a token. This is slightly longer than
433 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
434 // expiration exception.
435 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
436 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
437
438 // How long the service will remember expired tokens, for the purpose of providing error
439 // messaging when a client uses an expired token.
440 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
441 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
442
443 // Activity tokens of system activities that are delegating their call to
444 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
445 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
446
447 // Permission tokens that have expired, but we remember for error reporting.
448 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
449
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700450 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
451
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 // Keeps track of the active voice interaction service component, notified from
453 // VoiceInteractionManagerService
454 ComponentName mActiveVoiceInteractionServiceComponent;
455
Michal Karpinskida34cd42019-04-02 19:46:52 +0100456 // A map userId and all its companion app uids
457 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000458
Wale Ogunwalee2172292018-10-25 10:11:10 -0700459 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460 KeyguardController mKeyguardController;
461 private final ClientLifecycleManager mLifecycleManager;
462 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700463 /** The controller for all operations related to locktask. */
464 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700465 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700466
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 boolean mSuppressResizeConfigChanges;
468
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700469 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 new UpdateConfigurationResult();
471
472 static final class UpdateConfigurationResult {
473 // Configuration changes that were updated.
474 int changes;
475 // If the activity was relaunched to match the new configuration.
476 boolean activityRelaunched;
477
478 void reset() {
479 changes = 0;
480 activityRelaunched = false;
481 }
482 }
483
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485 private int mConfigurationSeq;
486 // To cache the list of supported system locales
487 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700488
489 /**
490 * Temp object used when global and/or display override configuration is updated. It is also
491 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
492 * anyone...
493 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 private Configuration mTempConfig = new Configuration();
495
Wale Ogunwalef6733932018-06-27 05:14:34 -0700496 /** Temporary to avoid allocations. */
497 final StringBuilder mStringBuilder = new StringBuilder(256);
498
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 // Amount of time after a call to stopAppSwitches() during which we will
500 // prevent further untrusted switches from happening.
501 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
502
503 /**
504 * The time at which we will allow normal application switches again,
505 * after a call to {@link #stopAppSwitches()}.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
509 * This is set to true after the first switch after mAppSwitchesAllowedTime
510 * is set; any switches after that will clear the time.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
Ricky Wai906af482019-06-03 17:25:28 +0100514 /**
515 * Last stop app switches time, apps finished before this time cannot start background activity
516 * even if they are in grace period.
517 */
518 private long mLastStopAppSwitchesTime;
519
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700520 IActivityController mController = null;
521 boolean mControllerIsAMonkey = false;
522
Wale Ogunwale214f3482018-10-04 11:00:47 -0700523 final int mFactoryTest;
524
525 /** Used to control how we initialize the service. */
526 ComponentName mTopComponent;
527 String mTopAction = Intent.ACTION_MAIN;
528 String mTopData;
529
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800530 /** Profiling app information. */
531 String mProfileApp = null;
532 WindowProcessController mProfileProc = null;
533 ProfilerInfo mProfilerInfo = null;
534
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700536 * Dump of the activity state at the time of the last ANR. Cleared after
537 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
538 */
539 String mLastANRState;
540
541 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542 * Used to retain an update lock when the foreground activity is in
543 * immersive mode.
544 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700545 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700546
547 /**
548 * Packages that are being allowed to perform unrestricted app switches. Mapping is
549 * User -> Type -> uid.
550 */
551 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
552
553 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700554 private int mThumbnailWidth;
555 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700556
557 /**
558 * Flag that indicates if multi-window is enabled.
559 *
560 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
561 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
562 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
563 * At least one of the forms of multi-window must be enabled in order for this flag to be
564 * initialized to 'true'.
565 *
566 * @see #mSupportsSplitScreenMultiWindow
567 * @see #mSupportsFreeformWindowManagement
568 * @see #mSupportsPictureInPicture
569 * @see #mSupportsMultiDisplay
570 */
571 boolean mSupportsMultiWindow;
572 boolean mSupportsSplitScreenMultiWindow;
573 boolean mSupportsFreeformWindowManagement;
574 boolean mSupportsPictureInPicture;
575 boolean mSupportsMultiDisplay;
576 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700577 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700578
579 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
580
581 // VR Vr2d Display Id.
582 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700583
Wale Ogunwalef6733932018-06-27 05:14:34 -0700584 /**
585 * Set while we are wanting to sleep, to prevent any
586 * activities from being started/resumed.
587 *
588 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
589 *
590 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
591 * while in the sleep state until there is a pending transition out of sleep, in which case
592 * mSleeping is set to false, and remains false while awake.
593 *
594 * Whether mSleeping can quickly toggled between true/false without the device actually
595 * display changing states is undefined.
596 */
597 private boolean mSleeping = false;
598
599 /**
600 * The process state used for processes that are running the top activities.
601 * This changes between TOP and TOP_SLEEPING to following mSleeping.
602 */
603 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
604
Riddle Hsua0022cd2019-09-09 21:12:41 +0800605 @Retention(RetentionPolicy.SOURCE)
606 @IntDef({
607 LAYOUT_REASON_CONFIG_CHANGED,
608 LAYOUT_REASON_VISIBILITY_CHANGED,
609 })
610 @interface LayoutReason {}
611 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
612 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
613
614 /** The reasons to perform surface placement. */
615 @LayoutReason
616 private int mLayoutReasons;
617
Wale Ogunwalef6733932018-06-27 05:14:34 -0700618 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
619 // automatically. Important for devices without direct input devices.
620 private boolean mShowDialogs = true;
621
622 /** Set if we are shutting down the system, similar to sleeping. */
623 boolean mShuttingDown = false;
624
625 /**
626 * We want to hold a wake lock while running a voice interaction session, since
627 * this may happen with the screen off and we need to keep the CPU running to
628 * be able to continue to interact with the user.
629 */
630 PowerManager.WakeLock mVoiceWakeLock;
631
632 /**
633 * Set while we are running a voice interaction. This overrides sleeping while it is active.
634 */
635 IVoiceInteractionSession mRunningVoice;
636
637 /**
638 * The last resumed activity. This is identical to the current resumed activity most
639 * of the time but could be different when we're pausing one activity before we resume
640 * another activity.
641 */
642 ActivityRecord mLastResumedActivity;
643
644 /**
645 * The activity that is currently being traced as the active resumed activity.
646 *
647 * @see #updateResumedAppTrace
648 */
649 private @Nullable ActivityRecord mTracedResumedActivity;
650
651 /** If non-null, we are tracking the time the user spends in the currently focused app. */
652 AppTimeTracker mCurAppTimeTracker;
653
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700654 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700655
Wale Ogunwale53783742018-09-16 10:21:51 -0700656 /**
657 * Packages that the user has asked to have run in screen size
658 * compatibility mode instead of filling the screen.
659 */
660 CompatModePackages mCompatModePackages;
661
Wale Ogunwalef6733932018-06-27 05:14:34 -0700662 private FontScaleSettingObserver mFontScaleSettingObserver;
663
Ricky Wai96f5c352019-04-10 18:40:17 +0100664 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000665
Wale Ogunwalef6733932018-06-27 05:14:34 -0700666 private final class FontScaleSettingObserver extends ContentObserver {
667 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
668 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
669
670 public FontScaleSettingObserver() {
671 super(mH);
672 final ContentResolver resolver = mContext.getContentResolver();
673 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
674 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
675 UserHandle.USER_ALL);
676 }
677
678 @Override
679 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
680 if (mFontScaleUri.equals(uri)) {
681 updateFontScaleIfNeeded(userId);
682 } else if (mHideErrorDialogsUri.equals(uri)) {
683 synchronized (mGlobalLock) {
684 updateShouldShowDialogsLocked(getGlobalConfiguration());
685 }
686 }
687 }
688 }
689
Riddle Hsua0536432019-02-16 00:38:59 +0800690 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
691 @Target(ElementType.METHOD)
692 @Retention(RetentionPolicy.SOURCE)
693 @interface HotPath {
694 int NONE = 0;
695 int OOM_ADJUSTMENT = 1;
696 int LRU_UPDATE = 2;
697 int PROCESS_CHANGE = 3;
698 int caller() default NONE;
699 }
700
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800701 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
702 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900703 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800704 mAmInternal.updateOomAdj();
705 }
706 };
707
Charles Chen8d98dd22018-12-26 17:36:54 +0800708 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
709 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700710 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700711 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700712 mSystemThread = ActivityThread.currentActivityThread();
713 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700714 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800715 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700717 }
718
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700719 public void onSystemReady() {
720 synchronized (mGlobalLock) {
721 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
722 PackageManager.FEATURE_CANT_SAVE_STATE);
723 mAssistUtils = new AssistUtils(mContext);
724 mVrController.onSystemReady();
725 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700726 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onInitPowerManagement() {
731 synchronized (mGlobalLock) {
732 mStackSupervisor.initPowerManagement();
733 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
734 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
735 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
736 mVoiceWakeLock.setReferenceCounted(false);
737 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700738 }
739
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700740 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700741 mFontScaleSettingObserver = new FontScaleSettingObserver();
742 }
743
Wale Ogunwale59507092018-10-29 09:00:30 -0700744 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700745 final boolean freeformWindowManagement =
746 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
747 || Settings.Global.getInt(
748 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
749
750 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
751 final boolean supportsPictureInPicture = supportsMultiWindow &&
752 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
753 final boolean supportsSplitScreenMultiWindow =
754 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
755 final boolean supportsMultiDisplay = mContext.getPackageManager()
756 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700757 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
758 final boolean forceResizable = Settings.Global.getInt(
759 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700760 final boolean sizeCompatFreeform = Settings.Global.getInt(
761 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700762
763 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900764 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765
766 final Configuration configuration = new Configuration();
767 Settings.System.getConfiguration(resolver, configuration);
768 if (forceRtl) {
769 // This will take care of setting the correct layout direction flags
770 configuration.setLayoutDirection(configuration.locale);
771 }
772
773 synchronized (mGlobalLock) {
774 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700775 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776 final boolean multiWindowFormEnabled = freeformWindowManagement
777 || supportsSplitScreenMultiWindow
778 || supportsPictureInPicture
779 || supportsMultiDisplay;
780 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
781 mSupportsMultiWindow = true;
782 mSupportsFreeformWindowManagement = freeformWindowManagement;
783 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
784 mSupportsPictureInPicture = supportsPictureInPicture;
785 mSupportsMultiDisplay = supportsMultiDisplay;
786 } else {
787 mSupportsMultiWindow = false;
788 mSupportsFreeformWindowManagement = false;
789 mSupportsSplitScreenMultiWindow = false;
790 mSupportsPictureInPicture = false;
791 mSupportsMultiDisplay = false;
792 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700793 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700794 // This happens before any activities are started, so we can change global configuration
795 // in-place.
796 updateConfigurationLocked(configuration, null, true);
797 final Configuration globalConfig = getGlobalConfiguration();
798 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
799
800 // Load resources only after the current configuration has been set.
801 final Resources res = mContext.getResources();
802 mThumbnailWidth = res.getDimensionPixelSize(
803 com.android.internal.R.dimen.thumbnail_width);
804 mThumbnailHeight = res.getDimensionPixelSize(
805 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 }
807 }
808
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800809 public WindowManagerGlobalLock getGlobalLock() {
810 return mGlobalLock;
811 }
812
Yunfan Chen585f2932019-01-29 16:04:45 +0900813 /** For test purpose only. */
814 @VisibleForTesting
815 public ActivityTaskManagerInternal getAtmInternal() {
816 return mInternal;
817 }
818
Riddle Hsud93a6c42018-11-29 21:50:06 +0800819 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
820 Looper looper) {
821 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700824 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800825 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700826 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700828 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700830 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700832 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700834 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700836 mKeyguardController = mStackSupervisor.getKeyguardController();
837 }
838
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700839 public void onActivityManagerInternalAdded() {
840 synchronized (mGlobalLock) {
841 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
842 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
843 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700844 }
845
Yunfan Chen75157d72018-07-27 14:47:21 +0900846 int increaseConfigurationSeqLocked() {
847 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
848 return mConfigurationSeq;
849 }
850
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700851 protected ActivityStackSupervisor createStackSupervisor() {
852 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
853 supervisor.initialize();
854 return supervisor;
855 }
856
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800857 protected AppWarnings createAppWarnings(
858 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
859 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
860 }
861
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700862 public void setWindowManager(WindowManagerService wm) {
863 synchronized (mGlobalLock) {
864 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800865 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800866 mTempConfig.setToDefaults();
867 mTempConfig.setLocales(LocaleList.getDefault());
868 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700870 mLockTaskController.setWindowManager(wm);
871 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800872 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700874 }
875
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700876 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
877 synchronized (mGlobalLock) {
878 mUsageStatsInternal = usageStatsManager;
879 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700880 }
881
Wale Ogunwalef6733932018-06-27 05:14:34 -0700882 UserManagerService getUserManager() {
883 if (mUserManager == null) {
884 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
885 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
886 }
887 return mUserManager;
888 }
889
890 AppOpsService getAppOpsService() {
891 if (mAppOpsService == null) {
892 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
893 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
894 }
895 return mAppOpsService;
896 }
897
898 boolean hasUserRestriction(String restriction, int userId) {
899 return getUserManager().hasUserRestriction(restriction, userId);
900 }
901
Michal Karpinski15486842019-04-25 17:33:42 +0100902 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
903 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700904 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100905 if (mode == AppOpsManager.MODE_DEFAULT) {
906 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
907 == PERMISSION_GRANTED;
908 }
909 return mode == AppOpsManager.MODE_ALLOWED;
910 }
911
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700912 @VisibleForTesting
913 protected void setRecentTasks(RecentTasks recentTasks) {
914 mRecentTasks = recentTasks;
915 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700916 }
917
918 RecentTasks getRecentTasks() {
919 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 }
921
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700922 ClientLifecycleManager getLifecycleManager() {
923 return mLifecycleManager;
924 }
925
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700926 ActivityStartController getActivityStartController() {
927 return mActivityStartController;
928 }
929
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700930 TaskChangeNotificationController getTaskChangeNotificationController() {
931 return mTaskChangeNotificationController;
932 }
933
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700934 LockTaskController getLockTaskController() {
935 return mLockTaskController;
936 }
937
Yunfan Chen75157d72018-07-27 14:47:21 +0900938 /**
939 * Return the global configuration used by the process corresponding to the input pid. This is
940 * usually the global configuration with some overrides specific to that process.
941 */
942 Configuration getGlobalConfigurationForCallingPid() {
943 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800944 return getGlobalConfigurationForPid(pid);
945 }
946
947 /**
948 * Return the global configuration used by the process corresponding to the given pid.
949 */
950 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900951 if (pid == MY_PID || pid < 0) {
952 return getGlobalConfiguration();
953 }
954 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100955 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900956 return app != null ? app.getConfiguration() : getGlobalConfiguration();
957 }
958 }
959
960 /**
961 * Return the device configuration info used by the process corresponding to the input pid.
962 * The value is consistent with the global configuration for the process.
963 */
964 @Override
965 public ConfigurationInfo getDeviceConfigurationInfo() {
966 ConfigurationInfo config = new ConfigurationInfo();
967 synchronized (mGlobalLock) {
968 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
969 config.reqTouchScreen = globalConfig.touchscreen;
970 config.reqKeyboardType = globalConfig.keyboard;
971 config.reqNavigation = globalConfig.navigation;
972 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
973 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
974 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
975 }
976 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
977 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
978 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
979 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700980 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900981 }
982 return config;
983 }
984
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700985 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700986 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700987 }
988
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700989 public static final class Lifecycle extends SystemService {
990 private final ActivityTaskManagerService mService;
991
992 public Lifecycle(Context context) {
993 super(context);
994 mService = new ActivityTaskManagerService(context);
995 }
996
997 @Override
998 public void onStart() {
999 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001000 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001001 }
1002
Garfield Tan891146c2018-10-09 12:14:00 -07001003 @Override
1004 public void onUnlockUser(int userId) {
1005 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001006 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001007 }
1008 }
1009
1010 @Override
1011 public void onCleanupUser(int userId) {
1012 synchronized (mService.getGlobalLock()) {
1013 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1014 }
1015 }
1016
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001017 public ActivityTaskManagerService getService() {
1018 return mService;
1019 }
1020 }
1021
1022 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 public final int startActivity(IApplicationThread caller, String callingPackage,
1024 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1025 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1026 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1027 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1028 UserHandle.getCallingUserId());
1029 }
1030
1031 @Override
1032 public final int startActivities(IApplicationThread caller, String callingPackage,
1033 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1034 int userId) {
1035 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001036 enforceNotIsolatedCaller(reason);
1037 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001039 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1040 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1041 reason, null /* originatingPendingIntent */,
1042 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 }
1044
1045 @Override
1046 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1047 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1048 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1049 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1050 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1051 true /*validateIncomingUser*/);
1052 }
1053
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001054 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1056 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1057 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001058 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001060 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1062
1063 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001064 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 .setCaller(caller)
1066 .setCallingPackage(callingPackage)
1067 .setResolvedType(resolvedType)
1068 .setResultTo(resultTo)
1069 .setResultWho(resultWho)
1070 .setRequestCode(requestCode)
1071 .setStartFlags(startFlags)
1072 .setProfilerInfo(profilerInfo)
1073 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001074 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 .execute();
1076
1077 }
1078
1079 @Override
1080 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1081 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1083 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 // Refuse possible leaked file descriptors
1085 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1086 throw new IllegalArgumentException("File descriptors passed in Intent");
1087 }
1088
1089 if (!(target instanceof PendingIntentRecord)) {
1090 throw new IllegalArgumentException("Bad PendingIntent object");
1091 }
1092
1093 PendingIntentRecord pir = (PendingIntentRecord)target;
1094
1095 synchronized (mGlobalLock) {
1096 // If this is coming from the currently resumed activity, it is
1097 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001098 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 if (stack.mResumedActivity != null &&
1100 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001101 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001102 }
1103 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001104 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 }
1107
1108 @Override
1109 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1110 Bundle bOptions) {
1111 // Refuse possible leaked file descriptors
1112 if (intent != null && intent.hasFileDescriptors()) {
1113 throw new IllegalArgumentException("File descriptors passed in Intent");
1114 }
1115 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1116
1117 synchronized (mGlobalLock) {
1118 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1119 if (r == null) {
1120 SafeActivityOptions.abort(options);
1121 return false;
1122 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001123 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 // The caller is not running... d'oh!
1125 SafeActivityOptions.abort(options);
1126 return false;
1127 }
1128 intent = new Intent(intent);
1129 // The caller is not allowed to change the data.
1130 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1131 // And we are resetting to find the next component...
1132 intent.setComponent(null);
1133
1134 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1135
1136 ActivityInfo aInfo = null;
1137 try {
1138 List<ResolveInfo> resolves =
1139 AppGlobals.getPackageManager().queryIntentActivities(
1140 intent, r.resolvedType,
1141 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1142 UserHandle.getCallingUserId()).getList();
1143
1144 // Look for the original activity in the list...
1145 final int N = resolves != null ? resolves.size() : 0;
1146 for (int i=0; i<N; i++) {
1147 ResolveInfo rInfo = resolves.get(i);
1148 if (rInfo.activityInfo.packageName.equals(r.packageName)
1149 && rInfo.activityInfo.name.equals(r.info.name)) {
1150 // We found the current one... the next matching is
1151 // after it.
1152 i++;
1153 if (i<N) {
1154 aInfo = resolves.get(i).activityInfo;
1155 }
1156 if (debug) {
1157 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1158 + "/" + r.info.name);
1159 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1160 ? "null" : aInfo.packageName + "/" + aInfo.name));
1161 }
1162 break;
1163 }
1164 }
1165 } catch (RemoteException e) {
1166 }
1167
1168 if (aInfo == null) {
1169 // Nobody who is next!
1170 SafeActivityOptions.abort(options);
1171 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1172 return false;
1173 }
1174
1175 intent.setComponent(new ComponentName(
1176 aInfo.applicationInfo.packageName, aInfo.name));
1177 intent.setFlags(intent.getFlags()&~(
1178 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1179 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1180 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1181 FLAG_ACTIVITY_NEW_TASK));
1182
1183 // Okay now we need to start the new activity, replacing the currently running activity.
1184 // This is a little tricky because we want to start the new one as if the current one is
1185 // finished, but not finish the current one first so that there is no flicker.
1186 // And thus...
1187 final boolean wasFinishing = r.finishing;
1188 r.finishing = true;
1189
1190 // Propagate reply information over to the new activity.
1191 final ActivityRecord resultTo = r.resultTo;
1192 final String resultWho = r.resultWho;
1193 final int requestCode = r.requestCode;
1194 r.resultTo = null;
1195 if (resultTo != null) {
1196 resultTo.removeResultsLocked(r, resultWho, requestCode);
1197 }
1198
1199 final long origId = Binder.clearCallingIdentity();
1200 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001201 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001202 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001203 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001204 .setResolvedType(r.resolvedType)
1205 .setActivityInfo(aInfo)
1206 .setResultTo(resultTo != null ? resultTo.appToken : null)
1207 .setResultWho(resultWho)
1208 .setRequestCode(requestCode)
1209 .setCallingPid(-1)
1210 .setCallingUid(r.launchedFromUid)
1211 .setCallingPackage(r.launchedFromPackage)
1212 .setRealCallingPid(-1)
1213 .setRealCallingUid(r.launchedFromUid)
1214 .setActivityOptions(options)
1215 .execute();
1216 Binder.restoreCallingIdentity(origId);
1217
1218 r.finishing = wasFinishing;
1219 if (res != ActivityManager.START_SUCCESS) {
1220 return false;
1221 }
1222 return true;
1223 }
1224 }
1225
1226 @Override
1227 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1228 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1229 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1230 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001231 enforceNotIsolatedCaller("startActivityAndWait");
1232 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1233 userId, "startActivityAndWait");
1234 // TODO: Switch to user app stacks here.
1235 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1236 .setCaller(caller)
1237 .setCallingPackage(callingPackage)
1238 .setResolvedType(resolvedType)
1239 .setResultTo(resultTo)
1240 .setResultWho(resultWho)
1241 .setRequestCode(requestCode)
1242 .setStartFlags(startFlags)
1243 .setActivityOptions(bOptions)
1244 .setUserId(userId)
1245 .setProfilerInfo(profilerInfo)
1246 .setWaitResult(res)
1247 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001248 return res;
1249 }
1250
1251 @Override
1252 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1253 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1254 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001255 enforceNotIsolatedCaller("startActivityWithConfig");
1256 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1257 "startActivityWithConfig");
1258 // TODO: Switch to user app stacks here.
1259 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1260 .setCaller(caller)
1261 .setCallingPackage(callingPackage)
1262 .setResolvedType(resolvedType)
1263 .setResultTo(resultTo)
1264 .setResultWho(resultWho)
1265 .setRequestCode(requestCode)
1266 .setStartFlags(startFlags)
1267 .setGlobalConfiguration(config)
1268 .setActivityOptions(bOptions)
1269 .setUserId(userId)
1270 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 }
1272
Alison Cichowlas3e340502018-08-07 17:15:01 -04001273
1274 @Override
1275 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1276 int callingUid = Binder.getCallingUid();
1277 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1278 throw new SecurityException("Only the system process can request a permission token, "
1279 + "received request from uid: " + callingUid);
1280 }
1281 IBinder permissionToken = new Binder();
1282 synchronized (mGlobalLock) {
1283 mStartActivitySources.put(permissionToken, delegatorToken);
1284 }
1285
1286 Message expireMsg = PooledLambda.obtainMessage(
1287 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1288 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1289
1290 Message forgetMsg = PooledLambda.obtainMessage(
1291 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1292 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1293
1294 return permissionToken;
1295 }
1296
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 @Override
1298 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1299 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001300 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1301 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001302 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001303 // permission grants) as any app that may launch one of your own activities. So we only
1304 // allow this in two cases:
1305 // 1) The caller is an activity that is part of the core framework, and then only when it
1306 // is running as the system.
1307 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1308 // can only be requested by a system activity, which may then delegate this call to
1309 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 final ActivityRecord sourceRecord;
1311 final int targetUid;
1312 final String targetPackage;
1313 final boolean isResolver;
1314 synchronized (mGlobalLock) {
1315 if (resultTo == null) {
1316 throw new SecurityException("Must be called from an activity");
1317 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001318 final IBinder sourceToken;
1319 if (permissionToken != null) {
1320 // To even attempt to use a permissionToken, an app must also have this signature
1321 // permission.
1322 mAmInternal.enforceCallingPermission(
1323 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1324 "startActivityAsCaller");
1325 // If called with a permissionToken, we want the sourceRecord from the delegator
1326 // activity that requested this token.
1327 sourceToken = mStartActivitySources.remove(permissionToken);
1328 if (sourceToken == null) {
1329 // Invalid permissionToken, check if it recently expired.
1330 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1331 throw new SecurityException("Called with expired permission token: "
1332 + permissionToken);
1333 } else {
1334 throw new SecurityException("Called with invalid permission token: "
1335 + permissionToken);
1336 }
1337 }
1338 } else {
1339 // This method was called directly by the source.
1340 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001342
Louis Chang149d5c82019-12-30 09:47:39 +08001343 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001344 if (sourceRecord == null) {
1345 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 }
1347 if (sourceRecord.app == null) {
1348 throw new SecurityException("Called without a process attached to activity");
1349 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001350
1351 // Whether called directly or from a delegate, the source activity must be from the
1352 // android package.
1353 if (!sourceRecord.info.packageName.equals("android")) {
1354 throw new SecurityException("Must be called from an activity that is "
1355 + "declared in the android package");
1356 }
1357
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001358 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 // This is still okay, as long as this activity is running under the
1360 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001361 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001363 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 + " must be system uid or original calling uid "
1365 + sourceRecord.launchedFromUid);
1366 }
1367 }
1368 if (ignoreTargetSecurity) {
1369 if (intent.getComponent() == null) {
1370 throw new SecurityException(
1371 "Component must be specified with ignoreTargetSecurity");
1372 }
1373 if (intent.getSelector() != null) {
1374 throw new SecurityException(
1375 "Selector not allowed with ignoreTargetSecurity");
1376 }
1377 }
1378 targetUid = sourceRecord.launchedFromUid;
1379 targetPackage = sourceRecord.launchedFromPackage;
1380 isResolver = sourceRecord.isResolverOrChildActivity();
1381 }
1382
1383 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001384 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 }
1386
1387 // TODO: Switch to user app stacks here.
1388 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001389 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 .setCallingUid(targetUid)
1391 .setCallingPackage(targetPackage)
1392 .setResolvedType(resolvedType)
1393 .setResultTo(resultTo)
1394 .setResultWho(resultWho)
1395 .setRequestCode(requestCode)
1396 .setStartFlags(startFlags)
1397 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001398 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1400 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001401 // The target may well be in the background, which would normally prevent it
1402 // from starting an activity. Here we definitely want the start to succeed.
1403 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 .execute();
1405 } catch (SecurityException e) {
1406 // XXX need to figure out how to propagate to original app.
1407 // A SecurityException here is generally actually a fault of the original
1408 // calling activity (such as a fairly granting permissions), so propagate it
1409 // back to them.
1410 /*
1411 StringBuilder msg = new StringBuilder();
1412 msg.append("While launching");
1413 msg.append(intent.toString());
1414 msg.append(": ");
1415 msg.append(e.getMessage());
1416 */
1417 throw e;
1418 }
1419 }
1420
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001421 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1422 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1423 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1424 }
1425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 @Override
1427 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1428 Intent intent, String resolvedType, IVoiceInteractionSession session,
1429 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1430 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 if (session == null || interactor == null) {
1433 throw new NullPointerException("null session or interactor");
1434 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001437 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 .setCallingUid(callingUid)
1439 .setCallingPackage(callingPackage)
1440 .setResolvedType(resolvedType)
1441 .setVoiceSession(session)
1442 .setVoiceInteractor(interactor)
1443 .setStartFlags(startFlags)
1444 .setProfilerInfo(profilerInfo)
1445 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001446 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001447 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 .execute();
1449 }
1450
1451 @Override
1452 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1453 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001454 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1455 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001457 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 .setCallingUid(callingUid)
1459 .setCallingPackage(callingPackage)
1460 .setResolvedType(resolvedType)
1461 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001462 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001463 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 .execute();
1465 }
1466
Riddle Hsu609a8e22019-06-27 16:46:29 -06001467 /**
1468 * Start the recents activity to perform the recents animation.
1469 *
1470 * @param intent The intent to start the recents activity.
1471 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1472 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001474 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1475 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001476 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001478 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 final long origId = Binder.clearCallingIdentity();
1480 try {
1481 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001482 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1483 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001484 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001485
1486 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001487 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001488 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001489 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001490 if (recentsAnimationRunner == null) {
1491 anim.preloadRecentsActivity();
1492 } else {
1493 anim.startRecentsActivity(recentsAnimationRunner);
1494 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(origId);
1498 }
1499 }
1500
1501 @Override
1502 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001503 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 "startActivityFromRecents()");
1505
1506 final int callingPid = Binder.getCallingPid();
1507 final int callingUid = Binder.getCallingUid();
1508 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1509 final long origId = Binder.clearCallingIdentity();
1510 try {
1511 synchronized (mGlobalLock) {
1512 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1513 safeOptions);
1514 }
1515 } finally {
1516 Binder.restoreCallingIdentity(origId);
1517 }
1518 }
1519
1520 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001521 * Public API to check if the client is allowed to start an activity on specified display.
1522 *
1523 * If the target display is private or virtual, some restrictions will apply.
1524 *
1525 * @param displayId Target display id.
1526 * @param intent Intent used to launch the activity.
1527 * @param resolvedType The MIME type of the intent.
1528 * @param userId The id of the user for whom the call is made.
1529 * @return {@code true} if a call to start an activity on the target display should succeed and
1530 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1531 */
1532 @Override
1533 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1534 String resolvedType, int userId) {
1535 final int callingUid = Binder.getCallingUid();
1536 final int callingPid = Binder.getCallingPid();
1537 final long origId = Binder.clearCallingIdentity();
1538
1539 try {
1540 // Collect information about the target of the Intent.
1541 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1542 0 /* startFlags */, null /* profilerInfo */, userId,
1543 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1544 UserHandle.USER_NULL));
1545 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1546
1547 synchronized (mGlobalLock) {
1548 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1549 aInfo);
1550 }
1551 } finally {
1552 Binder.restoreCallingIdentity(origId);
1553 }
1554 }
1555
1556 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 * This is the internal entry point for handling Activity.finish().
1558 *
1559 * @param token The Binder token referencing the Activity we want to finish.
1560 * @param resultCode Result code, if any, from this Activity.
1561 * @param resultData Result data (Intent), if any, from this Activity.
1562 * @param finishTask Whether to finish the task associated with this Activity.
1563 *
1564 * @return Returns true if the activity successfully finished, or false if it is still running.
1565 */
1566 @Override
1567 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1568 int finishTask) {
1569 // Refuse possible leaked file descriptors
1570 if (resultData != null && resultData.hasFileDescriptors()) {
1571 throw new IllegalArgumentException("File descriptors passed in Intent");
1572 }
1573
1574 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 if (r == null) {
1577 return true;
1578 }
1579 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001580 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001581 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 if (rootR == null) {
1583 Slog.w(TAG, "Finishing task with all activities already finished");
1584 }
1585 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1586 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001587 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 return false;
1589 }
1590
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001591 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1592 // We should consolidate.
1593 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001594 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001595 final ActivityRecord next =
1596 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 if (next != null) {
1598 // ask watcher if this is allowed
1599 boolean resumeOK = true;
1600 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001601 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001602 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001603 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001604 Watchdog.getInstance().setActivityController(null);
1605 }
1606
1607 if (!resumeOK) {
1608 Slog.i(TAG, "Not finishing activity because controller resumed");
1609 return false;
1610 }
1611 }
1612 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001613
1614 // note down that the process has finished an activity and is in background activity
1615 // starts grace period
1616 if (r.app != null) {
1617 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1618 }
1619
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001621 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 try {
1623 boolean res;
1624 final boolean finishWithRootActivity =
1625 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1626 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1627 || (finishWithRootActivity && r == rootR)) {
1628 // If requested, remove the task that is associated to this activity only if it
1629 // was the root activity in the task. The result code and data is ignored
1630 // because we don't support returning them across task boundaries. Also, to
1631 // keep backwards compatibility we remove the task from recents when finishing
1632 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001633 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001635 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001636 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001637 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001639 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001640 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 if (!res) {
1642 Slog.i(TAG, "Failed to finish by app-request");
1643 }
1644 }
1645 return res;
1646 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001647 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 Binder.restoreCallingIdentity(origId);
1649 }
1650 }
1651 }
1652
1653 @Override
1654 public boolean finishActivityAffinity(IBinder token) {
1655 synchronized (mGlobalLock) {
1656 final long origId = Binder.clearCallingIdentity();
1657 try {
1658 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1659 if (r == null) {
1660 return false;
1661 }
1662
1663 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1664 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001665 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 return false;
1667 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001668
1669 final PooledFunction p = PooledLambda.obtainFunction(
1670 ActivityRecord::finishIfSameAffinity, r,
1671 PooledLambda.__(ActivityRecord.class));
1672 r.getTask().forAllActivities(
1673 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1674 p.recycle();
1675
Andrii Kuliande93eff2019-07-12 12:21:27 -07001676 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 } finally {
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680 }
1681 }
1682
1683 @Override
1684 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1685 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001686 try {
1687 WindowProcessController proc = null;
1688 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001689 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001690 ActivityStack stack = ActivityRecord.getStackLocked(token);
1691 if (stack == null) {
1692 return;
1693 }
1694 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1695 false /* fromTimeout */, false /* processPausingActivities */, config);
1696 if (r != null) {
1697 proc = r.app;
1698 }
1699 if (stopProfiling && proc != null) {
1700 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 }
1702 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001703 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001704 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001705 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001706 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 }
1708
1709 @Override
1710 public final void activityResumed(IBinder token) {
1711 final long origId = Binder.clearCallingIdentity();
1712 synchronized (mGlobalLock) {
1713 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 }
1715 Binder.restoreCallingIdentity(origId);
1716 }
1717
1718 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001719 public final void activityTopResumedStateLost() {
1720 final long origId = Binder.clearCallingIdentity();
1721 synchronized (mGlobalLock) {
1722 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1723 }
1724 Binder.restoreCallingIdentity(origId);
1725 }
1726
1727 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 public final void activityPaused(IBinder token) {
1729 final long origId = Binder.clearCallingIdentity();
1730 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001731 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001732 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1733 if (r != null) {
1734 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001736 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001737 }
1738 Binder.restoreCallingIdentity(origId);
1739 }
1740
1741 @Override
1742 public final void activityStopped(IBinder token, Bundle icicle,
1743 PersistableBundle persistentState, CharSequence description) {
1744 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1745
1746 // Refuse possible leaked file descriptors
1747 if (icicle != null && icicle.hasFileDescriptors()) {
1748 throw new IllegalArgumentException("File descriptors passed in Bundle");
1749 }
1750
1751 final long origId = Binder.clearCallingIdentity();
1752
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001753 String restartingName = null;
1754 int restartingUid = 0;
1755 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001757 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001758 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001760 if (r.attachedToProcess()
1761 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1762 // The activity was requested to restart from
1763 // {@link #restartActivityProcessIfVisible}.
1764 restartingName = r.app.mName;
1765 restartingUid = r.app.mUid;
1766 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001767 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001768 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001769 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 }
1771
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001772 if (restartingName != null) {
1773 // In order to let the foreground activity can be restarted with its saved state from
1774 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1775 // until the activity reports stopped with the state. And the activity record will be
1776 // kept because the record state is restarting, then the activity will be restarted
1777 // immediately if it is still the top one.
1778 mStackSupervisor.removeRestartTimeouts(r);
1779 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1780 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001781 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001782
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785
1786 @Override
1787 public final void activityDestroyed(IBinder token) {
1788 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1789 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001790 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001791 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001792 try {
1793 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1794 if (activity != null) {
1795 activity.destroyed("activityDestroyed");
1796 }
1797 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001798 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001799 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
1801 }
1802 }
1803
1804 @Override
1805 public final void activityRelaunched(IBinder token) {
1806 final long origId = Binder.clearCallingIdentity();
1807 synchronized (mGlobalLock) {
1808 mStackSupervisor.activityRelaunchedLocked(token);
1809 }
1810 Binder.restoreCallingIdentity(origId);
1811 }
1812
1813 public final void activitySlept(IBinder token) {
1814 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1815
1816 final long origId = Binder.clearCallingIdentity();
1817
1818 synchronized (mGlobalLock) {
1819 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1820 if (r != null) {
1821 mStackSupervisor.activitySleptLocked(r);
1822 }
1823 }
1824
1825 Binder.restoreCallingIdentity(origId);
1826 }
1827
1828 @Override
1829 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1830 synchronized (mGlobalLock) {
1831 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1832 if (r == null) {
1833 return;
1834 }
1835 final long origId = Binder.clearCallingIdentity();
1836 try {
1837 r.setRequestedOrientation(requestedOrientation);
1838 } finally {
1839 Binder.restoreCallingIdentity(origId);
1840 }
1841 }
1842 }
1843
1844 @Override
1845 public int getRequestedOrientation(IBinder token) {
1846 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001847 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1848 return (r != null)
1849 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001850 }
1851 }
1852
1853 @Override
1854 public void setImmersive(IBinder token, boolean immersive) {
1855 synchronized (mGlobalLock) {
1856 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1857 if (r == null) {
1858 throw new IllegalArgumentException();
1859 }
1860 r.immersive = immersive;
1861
1862 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001863 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001864 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001865 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001866 }
1867 }
1868 }
1869
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 void applyUpdateLockStateLocked(ActivityRecord r) {
1871 // Modifications to the UpdateLock state are done on our handler, outside
1872 // the activity manager's locks. The new state is determined based on the
1873 // state *now* of the relevant activity record. The object is passed to
1874 // the handler solely for logging detail, not to be consulted/modified.
1875 final boolean nextState = r != null && r.immersive;
1876 mH.post(() -> {
1877 if (mUpdateLock.isHeld() != nextState) {
1878 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1879 "Applying new update lock state '" + nextState + "' for " + r);
1880 if (nextState) {
1881 mUpdateLock.acquire();
1882 } else {
1883 mUpdateLock.release();
1884 }
1885 }
1886 });
1887 }
1888
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 @Override
1890 public boolean isImmersive(IBinder token) {
1891 synchronized (mGlobalLock) {
1892 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1893 if (r == null) {
1894 throw new IllegalArgumentException();
1895 }
1896 return r.immersive;
1897 }
1898 }
1899
1900 @Override
1901 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001902 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001904 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 return (r != null) ? r.immersive : false;
1906 }
1907 }
1908
1909 @Override
1910 public void overridePendingTransition(IBinder token, String packageName,
1911 int enterAnim, int exitAnim) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1914 if (self == null) {
1915 return;
1916 }
1917
1918 final long origId = Binder.clearCallingIdentity();
1919
1920 if (self.isState(
1921 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001922 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001923 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001924 }
1925
1926 Binder.restoreCallingIdentity(origId);
1927 }
1928 }
1929
1930 @Override
1931 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001932 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001933 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001934 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001935 if (r == null) {
1936 return ActivityManager.COMPAT_MODE_UNKNOWN;
1937 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001938 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 }
1940 }
1941
1942 @Override
1943 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001944 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001946 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001948 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001949 if (r == null) {
1950 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1951 return;
1952 }
1953 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001954 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001955 }
1956 }
1957
1958 @Override
1959 public int getLaunchedFromUid(IBinder activityToken) {
1960 ActivityRecord srec;
1961 synchronized (mGlobalLock) {
1962 srec = ActivityRecord.forTokenLocked(activityToken);
1963 }
1964 if (srec == null) {
1965 return -1;
1966 }
1967 return srec.launchedFromUid;
1968 }
1969
1970 @Override
1971 public String getLaunchedFromPackage(IBinder activityToken) {
1972 ActivityRecord srec;
1973 synchronized (mGlobalLock) {
1974 srec = ActivityRecord.forTokenLocked(activityToken);
1975 }
1976 if (srec == null) {
1977 return null;
1978 }
1979 return srec.launchedFromPackage;
1980 }
1981
1982 @Override
1983 public boolean convertFromTranslucent(IBinder token) {
1984 final long origId = Binder.clearCallingIdentity();
1985 try {
1986 synchronized (mGlobalLock) {
1987 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1988 if (r == null) {
1989 return false;
1990 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001991 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 }
1993 } finally {
1994 Binder.restoreCallingIdentity(origId);
1995 }
1996 }
1997
1998 @Override
1999 public boolean convertToTranslucent(IBinder token, Bundle options) {
2000 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2001 final long origId = Binder.clearCallingIdentity();
2002 try {
2003 synchronized (mGlobalLock) {
2004 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2005 if (r == null) {
2006 return false;
2007 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002008 final ActivityRecord under = r.getTask().getActivityBelow(r);
2009 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2011 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002012 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(origId);
2016 }
2017 }
2018
2019 @Override
2020 public void notifyActivityDrawn(IBinder token) {
2021 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2022 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002023 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002024 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 }
2028 }
2029
2030 @Override
2031 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2032 synchronized (mGlobalLock) {
2033 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2034 if (r == null) {
2035 return;
2036 }
2037 r.reportFullyDrawnLocked(restoredFromBundle);
2038 }
2039 }
2040
2041 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002042 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 synchronized (mGlobalLock) {
2044 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2045 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2046 return stack.mDisplayId;
2047 }
2048 return DEFAULT_DISPLAY;
2049 }
2050 }
2051
2052 @Override
2053 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 long ident = Binder.clearCallingIdentity();
2056 try {
2057 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002058 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 if (focusedStack != null) {
Louis Chang149d5c82019-12-30 09:47:39 +08002060 return mRootWindowContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 }
2062 return null;
2063 }
2064 } finally {
2065 Binder.restoreCallingIdentity(ident);
2066 }
2067 }
2068
2069 @Override
2070 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002071 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2073 final long callingId = Binder.clearCallingIdentity();
2074 try {
2075 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002076 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 if (stack == null) {
2078 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2079 return;
2080 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002081 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002082 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002083 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 }
2085 }
2086 } finally {
2087 Binder.restoreCallingIdentity(callingId);
2088 }
2089 }
2090
2091 @Override
2092 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002093 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2095 final long callingId = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002098 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002099 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002100 if (task == null) {
2101 return;
2102 }
2103 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002104 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002105 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 }
2107 }
2108 } finally {
2109 Binder.restoreCallingIdentity(callingId);
2110 }
2111 }
2112
2113 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002114 public void restartActivityProcessIfVisible(IBinder activityToken) {
2115 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2116 final long callingId = Binder.clearCallingIdentity();
2117 try {
2118 synchronized (mGlobalLock) {
2119 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2120 if (r == null) {
2121 return;
2122 }
2123 r.restartProcessIfVisible();
2124 }
2125 } finally {
2126 Binder.restoreCallingIdentity(callingId);
2127 }
2128 }
2129
2130 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002132 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 synchronized (mGlobalLock) {
2134 final long ident = Binder.clearCallingIdentity();
2135 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002136 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 "remove-task");
2138 } finally {
2139 Binder.restoreCallingIdentity(ident);
2140 }
2141 }
2142 }
2143
2144 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002145 public void removeAllVisibleRecentTasks() {
2146 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2147 synchronized (mGlobalLock) {
2148 final long ident = Binder.clearCallingIdentity();
2149 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002150 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002151 } finally {
2152 Binder.restoreCallingIdentity(ident);
2153 }
2154 }
2155 }
2156
2157 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2159 synchronized (mGlobalLock) {
2160 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2161 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002162 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 }
2164 }
2165 return false;
2166 }
2167
2168 @Override
2169 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2170 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002171
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002172 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002173 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2174 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002175 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002176 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002177 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002178 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 }
2180 }
2181
2182 /**
2183 * Attempts to move a task backwards in z-order (the order of activities within the task is
2184 * unchanged).
2185 *
2186 * There are several possible results of this call:
2187 * - if the task is locked, then we will show the lock toast
2188 * - if there is a task behind the provided task, then that task is made visible and resumed as
2189 * this task is moved to the back
2190 * - otherwise, if there are no other tasks in the stack:
2191 * - if this task is in the pinned stack, then we remove the stack completely, which will
2192 * have the effect of moving the task to the top or bottom of the fullscreen stack
2193 * (depending on whether it is visible)
2194 * - otherwise, we simply return home and hide this task
2195 *
2196 * @param token A reference to the activity we wish to move
2197 * @param nonRoot If false then this only works if the activity is the root
2198 * of a task; if true it will work for any activity in a task.
2199 * @return Returns true if the move completed, false if not.
2200 */
2201 @Override
2202 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002203 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002204 synchronized (mGlobalLock) {
2205 final long origId = Binder.clearCallingIdentity();
2206 try {
2207 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002208 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002209 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002210 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 }
2212 } finally {
2213 Binder.restoreCallingIdentity(origId);
2214 }
2215 }
2216 return false;
2217 }
2218
2219 @Override
2220 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002221 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 long ident = Binder.clearCallingIdentity();
2223 Rect rect = new Rect();
2224 try {
2225 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002226 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2228 if (task == null) {
2229 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2230 return rect;
2231 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002232 if (task.getParent() != null) {
2233 rect.set(task.getBounds());
2234 } else if (task.mLastNonFullscreenBounds != null) {
2235 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 }
2237 }
2238 } finally {
2239 Binder.restoreCallingIdentity(ident);
2240 }
2241 return rect;
2242 }
2243
2244 @Override
2245 public ActivityManager.TaskDescription getTaskDescription(int id) {
2246 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002249 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002250 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2251 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002252 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002253 }
2254 }
2255 return null;
2256 }
2257
2258 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002259 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2260 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2261 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2262 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2263 return;
2264 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002266 synchronized (mGlobalLock) {
2267 final long ident = Binder.clearCallingIdentity();
2268 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002269 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002270 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 if (task == null) {
2272 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2273 return;
2274 }
2275
2276 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2277 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2278
2279 if (!task.isActivityTypeStandardOrUndefined()) {
2280 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2281 + " non-standard task " + taskId + " to windowing mode="
2282 + windowingMode);
2283 }
2284
2285 final ActivityStack stack = task.getStack();
2286 if (toTop) {
2287 stack.moveToFront("setTaskWindowingMode", task);
2288 }
2289 stack.setWindowingMode(windowingMode);
2290 } finally {
2291 Binder.restoreCallingIdentity(ident);
2292 }
2293 }
2294 }
2295
2296 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299 ActivityRecord r = getCallingRecordLocked(token);
2300 return r != null ? r.info.packageName : null;
2301 }
2302 }
2303
2304 @Override
2305 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002306 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002307 ActivityRecord r = getCallingRecordLocked(token);
2308 return r != null ? r.intent.getComponent() : null;
2309 }
2310 }
2311
2312 private ActivityRecord getCallingRecordLocked(IBinder token) {
2313 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2314 if (r == null) {
2315 return null;
2316 }
2317 return r.resultTo;
2318 }
2319
2320 @Override
2321 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323
2324 synchronized (mGlobalLock) {
2325 final long origId = Binder.clearCallingIdentity();
2326 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002327 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002328 } finally {
2329 Binder.restoreCallingIdentity(origId);
2330 }
2331 }
2332 }
2333
Mark Renouf446251d2019-04-26 10:22:41 -04002334 @Override
2335 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2336 synchronized (mGlobalLock) {
2337 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2338 if (r == null) {
2339 return;
2340 }
2341 ActivityStack stack = r.getActivityStack();
2342 if (stack != null && stack.isSingleTaskInstance()) {
2343 // Single-task stacks are used for activities which are presented in floating
2344 // windows above full screen activities. Instead of directly finishing the
2345 // task, a task change listener is used to notify SystemUI so the action can be
2346 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002347 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002348 mTaskChangeNotificationController
2349 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2350 } else {
2351 try {
2352 callback.requestFinish();
2353 } catch (RemoteException e) {
2354 Slog.e(TAG, "Failed to invoke request finish callback", e);
2355 }
2356 }
2357 }
2358 }
2359
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 /**
2361 * TODO: Add mController hook
2362 */
2363 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002364 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2365 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002367
2368 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2369 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2371 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002372 }
2373 }
2374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2376 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002378
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 final int callingPid = Binder.getCallingPid();
2380 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002381 if (!isSameApp(callingUid, callingPackage)) {
2382 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2383 + Binder.getCallingPid() + " as package " + callingPackage;
2384 Slog.w(TAG, msg);
2385 throw new SecurityException(msg);
2386 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002387 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 SafeActivityOptions.abort(options);
2389 return;
2390 }
2391 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002392 WindowProcessController callerApp = null;
2393 if (appThread != null) {
2394 callerApp = getProcessController(appThread);
2395 }
2396 final ActivityStarter starter = getActivityStartController().obtainStarter(
2397 null /* intent */, "moveTaskToFront");
2398 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2399 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002400 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002401 return;
2402 }
2403 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002405 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 if (task == null) {
2407 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002408 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 return;
2410 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002411 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002413 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002414 return;
2415 }
2416 ActivityOptions realOptions = options != null
2417 ? options.getOptions(mStackSupervisor)
2418 : null;
2419 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2420 false /* forceNonResizable */);
2421
Wale Ogunwale21e06482019-11-18 05:14:15 -08002422 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002423 if (topActivity != null) {
2424
2425 // We are reshowing a task, use a starting window to hide the initial draw delay
2426 // so the transition can start earlier.
2427 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2428 true /* taskSwitch */, fromRecents);
2429 }
2430 } finally {
2431 Binder.restoreCallingIdentity(origId);
2432 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002433 }
2434
Ricky Waiaca8a772019-04-04 16:01:06 +01002435 /**
2436 * Return true if callingUid is system, or packageName belongs to that callingUid.
2437 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002438 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002439 try {
2440 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2441 if (packageName == null) {
2442 return false;
2443 }
2444 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2445 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2446 UserHandle.getUserId(callingUid));
2447 return UserHandle.isSameApp(callingUid, uid);
2448 }
2449 } catch (RemoteException e) {
2450 // Should not happen
2451 }
2452 return true;
2453 }
2454
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2456 int callingPid, int callingUid, String name) {
2457 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2458 return true;
2459 }
2460
2461 if (getRecentTasks().isCallerRecents(sourceUid)) {
2462 return true;
2463 }
2464
2465 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2466 if (perm == PackageManager.PERMISSION_GRANTED) {
2467 return true;
2468 }
2469 if (checkAllowAppSwitchUid(sourceUid)) {
2470 return true;
2471 }
2472
2473 // If the actual IPC caller is different from the logical source, then
2474 // also see if they are allowed to control app switches.
2475 if (callingUid != -1 && callingUid != sourceUid) {
2476 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2477 if (perm == PackageManager.PERMISSION_GRANTED) {
2478 return true;
2479 }
2480 if (checkAllowAppSwitchUid(callingUid)) {
2481 return true;
2482 }
2483 }
2484
2485 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2486 return false;
2487 }
2488
2489 private boolean checkAllowAppSwitchUid(int uid) {
2490 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2491 if (types != null) {
2492 for (int i = types.size() - 1; i >= 0; i--) {
2493 if (types.valueAt(i).intValue() == uid) {
2494 return true;
2495 }
2496 }
2497 }
2498 return false;
2499 }
2500
2501 @Override
2502 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2503 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2504 "setActivityController()");
2505 synchronized (mGlobalLock) {
2506 mController = controller;
2507 mControllerIsAMonkey = imAMonkey;
2508 Watchdog.getInstance().setActivityController(controller);
2509 }
2510 }
2511
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002512 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002513 synchronized (mGlobalLock) {
2514 return mController != null && mControllerIsAMonkey;
2515 }
2516 }
2517
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 @Override
2519 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2520 synchronized (mGlobalLock) {
2521 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2522 }
2523 }
2524
2525 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2527 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2528 }
2529
2530 @Override
2531 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2532 @WindowConfiguration.ActivityType int ignoreActivityType,
2533 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2534 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002535 final int callingPid = Binder.getCallingPid();
2536 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002537 final int[] profileIds = getUserManager().getProfileIds(
2538 UserHandle.getUserId(callingUid), true);
2539 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2540 for (int i = 0; i < profileIds.length; i++) {
2541 callingProfileIds.add(profileIds[i]);
2542 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2544
2545 synchronized (mGlobalLock) {
2546 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2547
Nicholas Sauer0259e532019-08-30 08:24:55 -07002548 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002549 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002550 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 }
2552
2553 return list;
2554 }
2555
2556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2558 synchronized (mGlobalLock) {
2559 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002560 try {
2561 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2562 if (r == null) return;
2563
2564 final PooledConsumer c = PooledLambda.obtainConsumer(
2565 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2566 r, resultWho, requestCode);
2567 // TODO: This should probably only loop over the task since you need to be in the
2568 // same task to return results.
2569 r.getActivityStack().forAllActivities(c);
2570 c.recycle();
2571
2572 updateOomAdj();
2573 } finally {
2574 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
2577 }
2578
2579 @Override
2580 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002581 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002582 ActivityStack stack = ActivityRecord.getStackLocked(token);
2583 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002584 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002585 }
2586 return false;
2587 }
2588 }
2589
2590 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002591 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002592 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002593 synchronized (mGlobalLock) {
2594 final long ident = Binder.clearCallingIdentity();
2595 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002596 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002597 if (task == null) {
2598 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2599 return;
2600 }
2601
2602 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2603 + " to stackId=" + stackId + " toTop=" + toTop);
2604
Louis Chang149d5c82019-12-30 09:47:39 +08002605 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002606 if (stack == null) {
2607 throw new IllegalStateException(
2608 "moveTaskToStack: No stack for stackId=" + stackId);
2609 }
2610 if (!stack.isActivityTypeStandardOrUndefined()) {
2611 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2612 + taskId + " to stack " + stackId);
2613 }
2614 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002615 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2617 }
2618 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2619 "moveTaskToStack");
2620 } finally {
2621 Binder.restoreCallingIdentity(ident);
2622 }
2623 }
2624 }
2625
2626 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002627 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2628 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002629
2630 final long ident = Binder.clearCallingIdentity();
2631 try {
2632 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002633 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002634 if (stack == null) {
2635 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2636 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002637 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002638 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2639 throw new IllegalArgumentException("Stack: " + stackId
2640 + " doesn't support animated resize.");
2641 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002642 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002643 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002644 }
2645 } finally {
2646 Binder.restoreCallingIdentity(ident);
2647 }
2648 }
2649
wilsonshih5c4cf522019-01-25 09:03:47 +08002650 @Override
2651 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2652 int animationDuration) {
2653 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2654
2655 final long ident = Binder.clearCallingIdentity();
2656 try {
2657 synchronized (mGlobalLock) {
2658 if (xOffset == 0 && yOffset == 0) {
2659 return;
2660 }
Louis Chang149d5c82019-12-30 09:47:39 +08002661 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002662 if (stack == null) {
2663 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2664 return;
2665 }
2666 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2667 throw new IllegalArgumentException("Stack: " + stackId
2668 + " doesn't support animated resize.");
2669 }
2670 final Rect destBounds = new Rect();
2671 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002672 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002673 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2674 return;
2675 }
2676 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002677 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002678 animationDuration, false /* fromFullscreen */);
2679 }
2680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 /**
2685 * Moves the specified task to the primary-split-screen stack.
2686 *
2687 * @param taskId Id of task to move.
2688 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2689 * exist already. See
2690 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2691 * and
2692 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2693 * @param toTop If the task and stack should be moved to the top.
2694 * @param animate Whether we should play an animation for the moving the task.
2695 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2696 * stack. Pass {@code null} to use default bounds.
2697 * @param showRecents If the recents activity should be shown on the other side of the task
2698 * going into split-screen mode.
2699 */
2700 @Override
2701 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2702 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 "setTaskWindowingModeSplitScreenPrimary()");
2705 synchronized (mGlobalLock) {
2706 final long ident = Binder.clearCallingIdentity();
2707 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002708 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002709 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002710 if (task == null) {
2711 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2712 return false;
2713 }
2714 if (DEBUG_STACK) Slog.d(TAG_STACK,
2715 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2716 + " to createMode=" + createMode + " toTop=" + toTop);
2717 if (!task.isActivityTypeStandardOrUndefined()) {
2718 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2719 + " non-standard task " + taskId + " to split-screen windowing mode");
2720 }
2721
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002722 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 final int windowingMode = task.getWindowingMode();
2724 final ActivityStack stack = task.getStack();
2725 if (toTop) {
2726 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2727 }
2728 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002729 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2730 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002731 return windowingMode != task.getWindowingMode();
2732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736 }
2737
2738 /**
2739 * Removes stacks in the input windowing modes from the system if they are of activity type
2740 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2741 */
2742 @Override
2743 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002745 "removeStacksInWindowingModes()");
2746
2747 synchronized (mGlobalLock) {
2748 final long ident = Binder.clearCallingIdentity();
2749 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002750 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002751 } finally {
2752 Binder.restoreCallingIdentity(ident);
2753 }
2754 }
2755 }
2756
2757 @Override
2758 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002759 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002760 "removeStacksWithActivityTypes()");
2761
2762 synchronized (mGlobalLock) {
2763 final long ident = Binder.clearCallingIdentity();
2764 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002765 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
2769 }
2770 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771
2772 @Override
2773 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2774 int userId) {
2775 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002776 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2777 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002779 final boolean detailed = checkGetTasksPermission(
2780 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2781 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 == PackageManager.PERMISSION_GRANTED;
2783
2784 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002785 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 callingUid);
2787 }
2788 }
2789
2790 @Override
2791 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 long ident = Binder.clearCallingIdentity();
2794 try {
2795 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002796 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(ident);
2800 }
2801 }
2802
2803 @Override
2804 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 long ident = Binder.clearCallingIdentity();
2807 try {
2808 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002809 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002810 }
2811 } finally {
2812 Binder.restoreCallingIdentity(ident);
2813 }
2814 }
2815
2816 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002817 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2818 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2819 long ident = Binder.clearCallingIdentity();
2820 try {
2821 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002822 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002823 }
2824 } finally {
2825 Binder.restoreCallingIdentity(ident);
2826 }
2827 }
2828
2829 @Override
2830 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2831 int displayId) {
2832 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2833 long ident = Binder.clearCallingIdentity();
2834 try {
2835 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002836 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002837 }
2838 } finally {
2839 Binder.restoreCallingIdentity(ident);
2840 }
2841 }
2842
2843 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002845 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 final long callingUid = Binder.getCallingUid();
2847 final long origId = Binder.clearCallingIdentity();
2848 try {
2849 synchronized (mGlobalLock) {
2850 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002851 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2853 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2854 }
2855 } finally {
2856 Binder.restoreCallingIdentity(origId);
2857 }
2858 }
2859
2860 @Override
2861 public void startLockTaskModeByToken(IBinder token) {
2862 synchronized (mGlobalLock) {
2863 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2864 if (r == null) {
2865 return;
2866 }
Louis Changcdec0802019-11-11 11:45:07 +08002867 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 }
2869 }
2870
2871 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002872 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002873 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002874 // This makes inner call to look as if it was initiated by system.
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002878 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002879 MATCH_TASK_IN_STACKS_ONLY);
2880 if (task == null) {
2881 return;
2882 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883
2884 // When starting lock task mode the stack must be in front and focused
2885 task.getStack().moveToFront("startSystemLockTaskMode");
2886 startLockTaskModeLocked(task, true /* isSystemCaller */);
2887 }
2888 } finally {
2889 Binder.restoreCallingIdentity(ident);
2890 }
2891 }
2892
2893 @Override
2894 public void stopLockTaskModeByToken(IBinder token) {
2895 synchronized (mGlobalLock) {
2896 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2897 if (r == null) {
2898 return;
2899 }
Louis Changcdec0802019-11-11 11:45:07 +08002900 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901 }
2902 }
2903
2904 /**
2905 * This API should be called by SystemUI only when user perform certain action to dismiss
2906 * lock task mode. We should only dismiss pinned lock task mode in this case.
2907 */
2908 @Override
2909 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002910 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2912 }
2913
Louis Changcdec0802019-11-11 11:45:07 +08002914 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002915 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2916 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2917 return;
2918 }
2919
Louis Chang149d5c82019-12-30 09:47:39 +08002920 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002921 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 throw new IllegalArgumentException("Invalid task, not in foreground");
2923 }
2924
2925 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2926 // system or a specific app.
2927 // * System-initiated requests will only start the pinned mode (screen pinning)
2928 // * App-initiated requests
2929 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2930 // - will start the pinned mode, otherwise
2931 final int callingUid = Binder.getCallingUid();
2932 long ident = Binder.clearCallingIdentity();
2933 try {
2934 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002935 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002936
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002937 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 } finally {
2939 Binder.restoreCallingIdentity(ident);
2940 }
2941 }
2942
Louis Changcdec0802019-11-11 11:45:07 +08002943 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002944 final int callingUid = Binder.getCallingUid();
2945 long ident = Binder.clearCallingIdentity();
2946 try {
2947 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002948 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 }
2950 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2951 // task and jumping straight into a call in the case of emergency call back.
2952 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2953 if (tm != null) {
2954 tm.showInCallScreen(false);
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(ident);
2958 }
2959 }
2960
2961 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002962 public void updateLockTaskPackages(int userId, String[] packages) {
2963 final int callingUid = Binder.getCallingUid();
2964 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2965 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2966 "updateLockTaskPackages()");
2967 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002968 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002969 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2970 + Arrays.toString(packages));
2971 getLockTaskController().updateLockTaskPackages(userId, packages);
2972 }
2973 }
2974
2975 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002976 public boolean isInLockTaskMode() {
2977 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2978 }
2979
2980 @Override
2981 public int getLockTaskModeState() {
2982 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002983 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 }
2985 }
2986
2987 @Override
2988 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2991 if (r != null) {
2992 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002993 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 }
2996 }
2997 }
2998
2999 @Override
3000 public Bundle getActivityOptions(IBinder token) {
3001 final long origId = Binder.clearCallingIdentity();
3002 try {
3003 synchronized (mGlobalLock) {
3004 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3005 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003006 final ActivityOptions activityOptions = r.takeOptionsLocked(
3007 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 return activityOptions == null ? null : activityOptions.toBundle();
3009 }
3010 return null;
3011 }
3012 } finally {
3013 Binder.restoreCallingIdentity(origId);
3014 }
3015 }
3016
3017 @Override
3018 public List<IBinder> getAppTasks(String callingPackage) {
3019 int callingUid = Binder.getCallingUid();
3020 long ident = Binder.clearCallingIdentity();
3021 try {
3022 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003023 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 }
3025 } finally {
3026 Binder.restoreCallingIdentity(ident);
3027 }
3028 }
3029
3030 @Override
3031 public void finishVoiceTask(IVoiceInteractionSession session) {
3032 synchronized (mGlobalLock) {
3033 final long origId = Binder.clearCallingIdentity();
3034 try {
3035 // TODO: VI Consider treating local voice interactions and voice tasks
3036 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003037 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 } finally {
3039 Binder.restoreCallingIdentity(origId);
3040 }
3041 }
3042
3043 }
3044
3045 @Override
3046 public boolean isTopOfTask(IBinder token) {
3047 synchronized (mGlobalLock) {
3048 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003049 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 }
3051 }
3052
3053 @Override
3054 public void notifyLaunchTaskBehindComplete(IBinder token) {
3055 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3056 }
3057
3058 @Override
3059 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003060 mH.post(() -> {
3061 synchronized (mGlobalLock) {
3062 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003063 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003064 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003065 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003066 } catch (RemoteException e) {
3067 }
3068 }
3069 }
3070
3071 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 }
3073
3074 /** Called from an app when assist data is ready. */
3075 @Override
3076 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3077 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003078 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 synchronized (pae) {
3080 pae.result = extras;
3081 pae.structure = structure;
3082 pae.content = content;
3083 if (referrer != null) {
3084 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3085 }
3086 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003087 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003088 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003089 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 structure.setHomeActivity(pae.isHome);
3091 }
3092 pae.haveResult = true;
3093 pae.notifyAll();
3094 if (pae.intent == null && pae.receiver == null) {
3095 // Caller is just waiting for the result.
3096 return;
3097 }
3098 }
3099 // We are now ready to launch the assist activity.
3100 IAssistDataReceiver sendReceiver = null;
3101 Bundle sendBundle = null;
3102 synchronized (mGlobalLock) {
3103 buildAssistBundleLocked(pae, extras);
3104 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003105 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003106 if (!exists) {
3107 // Timed out.
3108 return;
3109 }
3110
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003111 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 // Caller wants result sent back to them.
3113 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003114 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003115 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003116 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3117 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3119 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3120 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3121 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3122 }
3123 }
3124 if (sendReceiver != null) {
3125 try {
3126 sendReceiver.onHandleAssistData(sendBundle);
3127 } catch (RemoteException e) {
3128 }
3129 return;
3130 }
3131
3132 final long ident = Binder.clearCallingIdentity();
3133 try {
3134 if (TextUtils.equals(pae.intent.getAction(),
3135 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003136 // Start voice interaction through VoiceInteractionManagerService.
3137 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3138 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 } else {
3140 pae.intent.replaceExtras(pae.extras);
3141 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3142 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3143 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003144 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145
3146 try {
3147 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3148 } catch (ActivityNotFoundException e) {
3149 Slog.w(TAG, "No activity to handle assist action.", e);
3150 }
3151 }
3152 } finally {
3153 Binder.restoreCallingIdentity(ident);
3154 }
3155 }
3156
3157 @Override
3158 public int addAppTask(IBinder activityToken, Intent intent,
3159 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3160 final int callingUid = Binder.getCallingUid();
3161 final long callingIdent = Binder.clearCallingIdentity();
3162
3163 try {
3164 synchronized (mGlobalLock) {
3165 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3166 if (r == null) {
3167 throw new IllegalArgumentException("Activity does not exist; token="
3168 + activityToken);
3169 }
3170 ComponentName comp = intent.getComponent();
3171 if (comp == null) {
3172 throw new IllegalArgumentException("Intent " + intent
3173 + " must specify explicit component");
3174 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003175 if (thumbnail.getWidth() != mThumbnailWidth
3176 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 throw new IllegalArgumentException("Bad thumbnail size: got "
3178 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003179 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 }
3181 if (intent.getSelector() != null) {
3182 intent.setSelector(null);
3183 }
3184 if (intent.getSourceBounds() != null) {
3185 intent.setSourceBounds(null);
3186 }
3187 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3188 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3189 // The caller has added this as an auto-remove task... that makes no
3190 // sense, so turn off auto-remove.
3191 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3192 }
3193 }
3194 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3195 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3196 if (ainfo.applicationInfo.uid != callingUid) {
3197 throw new SecurityException(
3198 "Can't add task for another application: target uid="
3199 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3200 }
3201
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003202 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003203 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003204 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003206 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003208 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003209 return INVALID_TASK_ID;
3210 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003211 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212
3213 // TODO: Send the thumbnail to WM to store it.
3214
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003215 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003216 }
3217 } finally {
3218 Binder.restoreCallingIdentity(callingIdent);
3219 }
3220 }
3221
3222 @Override
3223 public Point getAppTaskThumbnailSize() {
3224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003225 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226 }
3227 }
3228
3229 @Override
3230 public void setTaskResizeable(int taskId, int resizeableMode) {
3231 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003232 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3234 if (task == null) {
3235 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3236 return;
3237 }
3238 task.setResizeMode(resizeableMode);
3239 }
3240 }
3241
3242 @Override
3243 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003244 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 long ident = Binder.clearCallingIdentity();
3246 try {
3247 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003248 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003249 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 if (task == null) {
3251 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3252 return;
3253 }
3254 // Place the task in the right stack if it isn't there already based on
3255 // the requested bounds.
3256 // The stack transition logic is:
3257 // - a null bounds on a freeform task moves that task to fullscreen
3258 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3259 // that task to freeform
3260 // - otherwise the task is not moved
3261 ActivityStack stack = task.getStack();
3262 if (!task.getWindowConfiguration().canResizeTask()) {
3263 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3264 }
3265 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3266 stack = stack.getDisplay().getOrCreateStack(
3267 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3268 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3269 stack = stack.getDisplay().getOrCreateStack(
3270 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3271 }
3272
3273 // Reparent the task to the right stack if necessary
3274 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3275 if (stack != task.getStack()) {
3276 // Defer resume until the task is resized below
3277 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3278 DEFER_RESUME, "resizeTask");
3279 preserveWindow = false;
3280 }
3281
3282 // After reparenting (which only resizes the task to the stack bounds), resize the
3283 // task to the actual bounds provided
3284 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3285 }
3286 } finally {
3287 Binder.restoreCallingIdentity(ident);
3288 }
3289 }
3290
Evan Roskyddedfd42019-10-04 13:38:38 -07003291 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3292 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003293 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003294 throw new RuntimeException("Invalid token in task transaction");
3295 }
3296 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3297 // masks here.
3298 int configMask = change.getConfigSetMask();
3299 int windowMask = change.getWindowSetMask();
3300 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3301 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3302 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3303 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3304 c.setTo(change.getConfiguration(), configMask, windowMask);
3305 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003306 // TODO(b/145675353): remove the following once we could apply new bounds to the
3307 // pinned stack together with its children.
3308 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3309 }
3310
3311 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3312 int windowMask, Configuration config) {
3313 if ((container instanceof ActivityStack)
3314 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3315 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3316 final ActivityStack stack = (ActivityStack) container;
3317 if (stack.inPinnedWindowingMode()) {
3318 stack.resize(config.windowConfiguration.getBounds(),
3319 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3320 PRESERVE_WINDOWS, true /* deferResume */);
3321 }
3322 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003323 }
3324
3325 @Override
3326 public void applyContainerTransaction(WindowContainerTransaction t) {
3327 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3328 long ident = Binder.clearCallingIdentity();
3329 try {
3330 if (t == null) {
3331 return;
3332 }
3333 synchronized (mGlobalLock) {
3334 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3335 t.getChanges().entrySet().iterator();
3336 while (entries.hasNext()) {
3337 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3338 entries.next();
3339 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3340 entry.getKey()).getContainer();
3341 sanitizeAndApplyConfigChange(cc, entry.getValue());
3342 }
3343 }
3344 } finally {
3345 Binder.restoreCallingIdentity(ident);
3346 }
3347 }
3348
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003349 @Override
3350 public boolean releaseActivityInstance(IBinder token) {
3351 synchronized (mGlobalLock) {
3352 final long origId = Binder.clearCallingIdentity();
3353 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003354 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3355 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 return false;
3357 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003358 r.destroyImmediately(true /* removeFromApp */, "app-req");
3359 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003360 } finally {
3361 Binder.restoreCallingIdentity(origId);
3362 }
3363 }
3364 }
3365
3366 @Override
3367 public void releaseSomeActivities(IApplicationThread appInt) {
3368 synchronized (mGlobalLock) {
3369 final long origId = Binder.clearCallingIdentity();
3370 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003371 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003372 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003373 } finally {
3374 Binder.restoreCallingIdentity(origId);
3375 }
3376 }
3377 }
3378
3379 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003380 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003381 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 != PackageManager.PERMISSION_GRANTED) {
3383 throw new SecurityException("Requires permission "
3384 + android.Manifest.permission.DEVICE_POWER);
3385 }
3386
3387 synchronized (mGlobalLock) {
3388 long ident = Binder.clearCallingIdentity();
3389 if (mKeyguardShown != keyguardShowing) {
3390 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003391 final Message msg = PooledLambda.obtainMessage(
3392 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3393 keyguardShowing);
3394 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 }
3396 try {
wilsonshih177261f2019-02-22 12:02:18 +08003397 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 } finally {
3399 Binder.restoreCallingIdentity(ident);
3400 }
3401 }
3402
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003403 mH.post(() -> {
3404 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3405 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3406 }
3407 });
3408 }
3409
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003410 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003411 mH.post(() -> {
3412 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3413 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3414 }
3415 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 }
3417
3418 @Override
3419 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003420 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3421 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422
3423 final File passedIconFile = new File(filePath);
3424 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3425 passedIconFile.getName());
3426 if (!legitIconFile.getPath().equals(filePath)
3427 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3428 throw new IllegalArgumentException("Bad file path: " + filePath
3429 + " passed for userId " + userId);
3430 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003431 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
3434 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003436 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 synchronized (mGlobalLock) {
3438 final long ident = Binder.clearCallingIdentity();
3439 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003440 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003441 if (stack == null) {
3442 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3443 return;
3444 }
3445 if (!stack.isActivityTypeStandardOrUndefined()) {
3446 throw new IllegalArgumentException(
3447 "Removing non-standard stack is not allowed.");
3448 }
3449 mStackSupervisor.removeStack(stack);
3450 } finally {
3451 Binder.restoreCallingIdentity(ident);
3452 }
3453 }
3454 }
3455
3456 @Override
3457 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003458 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459
3460 synchronized (mGlobalLock) {
3461 final long ident = Binder.clearCallingIdentity();
3462 try {
3463 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3464 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003465 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 } finally {
3467 Binder.restoreCallingIdentity(ident);
3468 }
3469 }
3470 }
3471
3472 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003473 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474 synchronized (mGlobalLock) {
3475 long ident = Binder.clearCallingIdentity();
3476 try {
3477 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3478 if (r == null) {
3479 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003480 "toggleFreeformWindowingMode: No activity record matching token="
3481 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 }
3483
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003484 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003485 if (stack == null) {
3486 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3487 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003488 }
3489
Yunfan Chend967af82019-01-17 18:30:18 +09003490 if (!stack.inFreeformWindowingMode()
3491 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3492 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3493 + "toggle between fullscreen and freeform.");
3494 }
3495
3496 if (stack.inFreeformWindowingMode()) {
3497 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003498 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003499 throw new IllegalStateException("Size-compat windows are currently not"
3500 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003501 } else if (stack.getParent().inFreeformWindowingMode()) {
3502 // If the window is on a freeform display, set it to undefined. It will be
3503 // resolved to freeform and it can adjust windowing mode when the display mode
3504 // changes in runtime.
3505 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003506 } else {
3507 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3508 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003509 } finally {
3510 Binder.restoreCallingIdentity(ident);
3511 }
3512 }
3513 }
3514
3515 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3516 @Override
3517 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003518 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003520 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 }
3522
3523 /** Unregister a task stack listener so that it stops receiving callbacks. */
3524 @Override
3525 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003526 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003528 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003529 }
3530
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003531 @Override
3532 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3533 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3534 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3535 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3536 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3537 }
3538
3539 @Override
3540 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3541 IBinder activityToken, int flags) {
3542 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3543 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3544 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3545 }
3546
3547 @Override
3548 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3549 Bundle args) {
3550 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3551 true /* focused */, true /* newSessionId */, userHandle, args,
3552 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3553 }
3554
3555 @Override
3556 public Bundle getAssistContextExtras(int requestType) {
3557 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3558 null, null, true /* focused */, true /* newSessionId */,
3559 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3560 if (pae == null) {
3561 return null;
3562 }
3563 synchronized (pae) {
3564 while (!pae.haveResult) {
3565 try {
3566 pae.wait();
3567 } catch (InterruptedException e) {
3568 }
3569 }
3570 }
3571 synchronized (mGlobalLock) {
3572 buildAssistBundleLocked(pae, pae.result);
3573 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003574 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003575 }
3576 return pae.extras;
3577 }
3578
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003579 /**
3580 * Binder IPC calls go through the public entry point.
3581 * This can be called with or without the global lock held.
3582 */
3583 private static int checkCallingPermission(String permission) {
3584 return checkPermission(
3585 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3586 }
3587
3588 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003589 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3591 mAmInternal.enforceCallingPermission(permission, func);
3592 }
3593 }
3594
3595 @VisibleForTesting
3596 int checkGetTasksPermission(String permission, int pid, int uid) {
3597 return checkPermission(permission, pid, uid);
3598 }
3599
3600 static int checkPermission(String permission, int pid, int uid) {
3601 if (permission == null) {
3602 return PackageManager.PERMISSION_DENIED;
3603 }
3604 return checkComponentPermission(permission, pid, uid, -1, true);
3605 }
3606
Wale Ogunwale214f3482018-10-04 11:00:47 -07003607 public static int checkComponentPermission(String permission, int pid, int uid,
3608 int owningUid, boolean exported) {
3609 return ActivityManagerService.checkComponentPermission(
3610 permission, pid, uid, owningUid, exported);
3611 }
3612
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003613 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3614 if (getRecentTasks().isCallerRecents(callingUid)) {
3615 // Always allow the recents component to get tasks
3616 return true;
3617 }
3618
3619 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3620 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3621 if (!allowed) {
3622 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3623 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3624 // Temporary compatibility: some existing apps on the system image may
3625 // still be requesting the old permission and not switched to the new
3626 // one; if so, we'll still allow them full access. This means we need
3627 // to see if they are holding the old permission and are a system app.
3628 try {
3629 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3630 allowed = true;
3631 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3632 + " is using old GET_TASKS but privileged; allowing");
3633 }
3634 } catch (RemoteException e) {
3635 }
3636 }
3637 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3638 + " does not hold REAL_GET_TASKS; limiting output");
3639 }
3640 return allowed;
3641 }
3642
Nicholas Sauer0259e532019-08-30 08:24:55 -07003643 boolean isCrossUserAllowed(int pid, int uid) {
3644 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3645 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3646 }
3647
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003648 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3649 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3650 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3651 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003652 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003653 "enqueueAssistContext()");
3654
3655 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003656 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003657 if (activity == null) {
3658 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3659 return null;
3660 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003661 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003662 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3663 return null;
3664 }
3665 if (focused) {
3666 if (activityToken != null) {
3667 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3668 if (activity != caller) {
3669 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3670 + " is not current top " + activity);
3671 return null;
3672 }
3673 }
3674 } else {
3675 activity = ActivityRecord.forTokenLocked(activityToken);
3676 if (activity == null) {
3677 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3678 + " couldn't be found");
3679 return null;
3680 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003681 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3683 return null;
3684 }
3685 }
3686
3687 PendingAssistExtras pae;
3688 Bundle extras = new Bundle();
3689 if (args != null) {
3690 extras.putAll(args);
3691 }
3692 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003693 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003694
3695 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3696 userHandle);
3697 pae.isHome = activity.isActivityTypeHome();
3698
3699 // Increment the sessionId if necessary
3700 if (newSessionId) {
3701 mViSessionId++;
3702 }
3703 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003704 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3705 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003706 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003707 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 } catch (RemoteException e) {
3709 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3710 return null;
3711 }
3712 return pae;
3713 }
3714 }
3715
3716 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3717 if (result != null) {
3718 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3719 }
3720 if (pae.hint != null) {
3721 pae.extras.putBoolean(pae.hint, true);
3722 }
3723 }
3724
3725 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3726 IAssistDataReceiver receiver;
3727 synchronized (mGlobalLock) {
3728 mPendingAssistExtras.remove(pae);
3729 receiver = pae.receiver;
3730 }
3731 if (receiver != null) {
3732 // Caller wants result sent back to them.
3733 Bundle sendBundle = new Bundle();
3734 // At least return the receiver extras
3735 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3736 try {
3737 pae.receiver.onHandleAssistData(sendBundle);
3738 } catch (RemoteException e) {
3739 }
3740 }
3741 }
3742
3743 public class PendingAssistExtras extends Binder implements Runnable {
3744 public final ActivityRecord activity;
3745 public boolean isHome;
3746 public final Bundle extras;
3747 public final Intent intent;
3748 public final String hint;
3749 public final IAssistDataReceiver receiver;
3750 public final int userHandle;
3751 public boolean haveResult = false;
3752 public Bundle result = null;
3753 public AssistStructure structure = null;
3754 public AssistContent content = null;
3755 public Bundle receiverExtras;
3756
3757 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3758 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3759 int _userHandle) {
3760 activity = _activity;
3761 extras = _extras;
3762 intent = _intent;
3763 hint = _hint;
3764 receiver = _receiver;
3765 receiverExtras = _receiverExtras;
3766 userHandle = _userHandle;
3767 }
3768
3769 @Override
3770 public void run() {
3771 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3772 synchronized (this) {
3773 haveResult = true;
3774 notifyAll();
3775 }
3776 pendingAssistExtrasTimedOut(this);
3777 }
3778 }
3779
3780 @Override
3781 public boolean isAssistDataAllowedOnCurrentActivity() {
3782 int userId;
3783 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003784 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3786 return false;
3787 }
3788
Wale Ogunwale21e06482019-11-18 05:14:15 -08003789 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003790 if (activity == null) {
3791 return false;
3792 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003793 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 }
3795 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3796 }
3797
3798 @Override
3799 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3800 long ident = Binder.clearCallingIdentity();
3801 try {
3802 synchronized (mGlobalLock) {
3803 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003804 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003805 if (top != caller) {
3806 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3807 + " is not current top " + top);
3808 return false;
3809 }
3810 if (!top.nowVisible) {
3811 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3812 + " is not visible");
3813 return false;
3814 }
3815 }
3816 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3817 token);
3818 } finally {
3819 Binder.restoreCallingIdentity(ident);
3820 }
3821 }
3822
3823 @Override
3824 public boolean isRootVoiceInteraction(IBinder token) {
3825 synchronized (mGlobalLock) {
3826 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3827 if (r == null) {
3828 return false;
3829 }
3830 return r.rootVoiceInteraction;
3831 }
3832 }
3833
Wale Ogunwalef6733932018-06-27 05:14:34 -07003834 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3835 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3836 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3837 if (activityToCallback == null) return;
3838 activityToCallback.setVoiceSessionLocked(voiceSession);
3839
3840 // Inform the activity
3841 try {
3842 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3843 voiceInteractor);
3844 long token = Binder.clearCallingIdentity();
3845 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003846 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003847 } finally {
3848 Binder.restoreCallingIdentity(token);
3849 }
3850 // TODO: VI Should we cache the activity so that it's easier to find later
3851 // rather than scan through all the stacks and activities?
3852 } catch (RemoteException re) {
3853 activityToCallback.clearVoiceSessionLocked();
3854 // TODO: VI Should this terminate the voice session?
3855 }
3856 }
3857
3858 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3859 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3860 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3861 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3862 boolean wasRunningVoice = mRunningVoice != null;
3863 mRunningVoice = session;
3864 if (!wasRunningVoice) {
3865 mVoiceWakeLock.acquire();
3866 updateSleepIfNeededLocked();
3867 }
3868 }
3869 }
3870
3871 void finishRunningVoiceLocked() {
3872 if (mRunningVoice != null) {
3873 mRunningVoice = null;
3874 mVoiceWakeLock.release();
3875 updateSleepIfNeededLocked();
3876 }
3877 }
3878
3879 @Override
3880 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3881 synchronized (mGlobalLock) {
3882 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3883 if (keepAwake) {
3884 mVoiceWakeLock.acquire();
3885 } else {
3886 mVoiceWakeLock.release();
3887 }
3888 }
3889 }
3890 }
3891
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003892 @Override
3893 public ComponentName getActivityClassForToken(IBinder token) {
3894 synchronized (mGlobalLock) {
3895 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3896 if (r == null) {
3897 return null;
3898 }
3899 return r.intent.getComponent();
3900 }
3901 }
3902
3903 @Override
3904 public String getPackageForToken(IBinder token) {
3905 synchronized (mGlobalLock) {
3906 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3907 if (r == null) {
3908 return null;
3909 }
3910 return r.packageName;
3911 }
3912 }
3913
3914 @Override
3915 public void showLockTaskEscapeMessage(IBinder token) {
3916 synchronized (mGlobalLock) {
3917 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3918 if (r == null) {
3919 return;
3920 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003921 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 }
3923 }
3924
3925 @Override
3926 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003927 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 final long token = Binder.clearCallingIdentity();
3929 try {
3930 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003931 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 }
3933 } finally {
3934 Binder.restoreCallingIdentity(token);
3935 }
3936 }
3937
3938 /**
3939 * Try to place task to provided position. The final position might be different depending on
3940 * current user and stacks state. The task will be moved to target stack if it's currently in
3941 * different stack.
3942 */
3943 @Override
3944 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003945 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 synchronized (mGlobalLock) {
3947 long ident = Binder.clearCallingIdentity();
3948 try {
3949 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3950 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003951 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 if (task == null) {
3953 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3954 + taskId);
3955 }
3956
Louis Chang149d5c82019-12-30 09:47:39 +08003957 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958
3959 if (stack == null) {
3960 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3961 + stackId);
3962 }
3963 if (!stack.isActivityTypeStandardOrUndefined()) {
3964 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3965 + " the position of task " + taskId + " in/to non-standard stack");
3966 }
3967
3968 // TODO: Have the callers of this API call a separate reparent method if that is
3969 // what they intended to do vs. having this method also do reparenting.
3970 if (task.getStack() == stack) {
3971 // Change position in current stack.
3972 stack.positionChildAt(task, position);
3973 } else {
3974 // Reparent to new stack.
3975 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3976 !DEFER_RESUME, "positionTaskInStack");
3977 }
3978 } finally {
3979 Binder.restoreCallingIdentity(ident);
3980 }
3981 }
3982 }
3983
3984 @Override
3985 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3986 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3987 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003988 + Arrays.toString(horizontalSizeConfiguration) + " "
3989 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 synchronized (mGlobalLock) {
3991 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3992 if (record == null) {
3993 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3994 + "found for: " + token);
3995 }
3996 record.setSizeConfigurations(horizontalSizeConfiguration,
3997 verticalSizeConfigurations, smallestSizeConfigurations);
3998 }
3999 }
4000
4001 /**
4002 * Dismisses split-screen multi-window mode.
4003 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4004 */
4005 @Override
4006 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4009 final long ident = Binder.clearCallingIdentity();
4010 try {
4011 synchronized (mGlobalLock) {
4012 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004013 mRootWindowContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 if (stack == null) {
4015 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4016 return;
4017 }
4018
4019 if (toTop) {
4020 // Caller wants the current split-screen primary stack to be the top stack after
4021 // it goes fullscreen, so move it to the front.
4022 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004023 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004025 // stack after it goes fullscreen, so we move the focus to the top-most
4026 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4028 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4029 if (otherStack != null) {
4030 otherStack.moveToFront("dismissSplitScreenMode_other");
4031 }
4032 }
4033
Evan Rosky10475742018-09-05 19:02:48 -07004034 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 }
4036 } finally {
4037 Binder.restoreCallingIdentity(ident);
4038 }
4039 }
4040
4041 /**
4042 * Dismisses Pip
4043 * @param animate True if the dismissal should be animated.
4044 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4045 * default animation duration should be used.
4046 */
4047 @Override
4048 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004049 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 final long ident = Binder.clearCallingIdentity();
4051 try {
4052 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004053 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004054 mRootWindowContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004055 if (stack == null) {
4056 Slog.w(TAG, "dismissPip: pinned stack not found.");
4057 return;
4058 }
4059 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4060 throw new IllegalArgumentException("Stack: " + stack
4061 + " doesn't support animated resize.");
4062 }
4063 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004064 stack.animateResizePinnedStack(null /* destBounds */,
4065 null /* sourceHintBounds */, animationDuration,
4066 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004068 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004069 }
4070 }
4071 } finally {
4072 Binder.restoreCallingIdentity(ident);
4073 }
4074 }
4075
4076 @Override
4077 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004078 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 synchronized (mGlobalLock) {
4080 mSuppressResizeConfigChanges = suppress;
4081 }
4082 }
4083
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004084 @Override
4085 // TODO: API should just be about changing windowing modes...
4086 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004087 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 "moveTasksToFullscreenStack()");
4089 synchronized (mGlobalLock) {
4090 final long origId = Binder.clearCallingIdentity();
4091 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004092 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093 if (stack != null){
4094 if (!stack.isActivityTypeStandardOrUndefined()) {
4095 throw new IllegalArgumentException(
4096 "You can't move tasks from non-standard stacks.");
4097 }
4098 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4099 }
4100 } finally {
4101 Binder.restoreCallingIdentity(origId);
4102 }
4103 }
4104 }
4105
4106 /**
4107 * Moves the top activity in the input stackId to the pinned stack.
4108 *
4109 * @param stackId Id of stack to move the top activity to pinned stack.
4110 * @param bounds Bounds to use for pinned stack.
4111 *
4112 * @return True if the top activity of the input stack was successfully moved to the pinned
4113 * stack.
4114 */
4115 @Override
4116 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 "moveTopActivityToPinnedStack()");
4119 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004120 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4122 + "Device doesn't support picture-in-picture mode");
4123 }
4124
4125 long ident = Binder.clearCallingIdentity();
4126 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004127 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004128 } finally {
4129 Binder.restoreCallingIdentity(ident);
4130 }
4131 }
4132 }
4133
4134 @Override
4135 public boolean isInMultiWindowMode(IBinder token) {
4136 final long origId = Binder.clearCallingIdentity();
4137 try {
4138 synchronized (mGlobalLock) {
4139 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4140 if (r == null) {
4141 return false;
4142 }
4143 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4144 return r.inMultiWindowMode();
4145 }
4146 } finally {
4147 Binder.restoreCallingIdentity(origId);
4148 }
4149 }
4150
4151 @Override
4152 public boolean isInPictureInPictureMode(IBinder token) {
4153 final long origId = Binder.clearCallingIdentity();
4154 try {
4155 synchronized (mGlobalLock) {
4156 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4157 }
4158 } finally {
4159 Binder.restoreCallingIdentity(origId);
4160 }
4161 }
4162
4163 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004164 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4165 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 return false;
4167 }
4168
4169 // If we are animating to fullscreen then we have already dispatched the PIP mode
4170 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004171 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004172 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 }
4174
4175 @Override
4176 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4177 final long origId = Binder.clearCallingIdentity();
4178 try {
4179 synchronized (mGlobalLock) {
4180 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4181 "enterPictureInPictureMode", token, params);
4182
4183 // If the activity is already in picture in picture mode, then just return early
4184 if (isInPictureInPictureMode(r)) {
4185 return true;
4186 }
4187
4188 // Activity supports picture-in-picture, now check that we can enter PiP at this
4189 // point, if it is
4190 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4191 false /* beforeStopping */)) {
4192 return false;
4193 }
4194
4195 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004196 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004197 if (r.getParent() == null) {
4198 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4199 return;
4200 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004201 // Only update the saved args from the args that are set
4202 r.pictureInPictureArgs.copyOnlySet(params);
4203 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4204 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4205 // Adjust the source bounds by the insets for the transition down
4206 final Rect sourceBounds = new Rect(
4207 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004208 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004209 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004210 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004211 stack.setPictureInPictureAspectRatio(aspectRatio);
4212 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004213 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4214 r.info.applicationInfo.uid, r.shortComponentName,
4215 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004216 logPictureInPictureArgs(params);
4217 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 };
4219
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004220 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 // If the keyguard is showing or occluded, then try and dismiss it before
4222 // entering picture-in-picture (this will prompt the user to authenticate if the
4223 // device is currently locked).
4224 dismissKeyguard(token, new KeyguardDismissCallback() {
4225 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004226 public void onDismissSucceeded() {
4227 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 }
4229 }, null /* message */);
4230 } else {
4231 // Enter picture in picture immediately otherwise
4232 enterPipRunnable.run();
4233 }
4234 return true;
4235 }
4236 } finally {
4237 Binder.restoreCallingIdentity(origId);
4238 }
4239 }
4240
4241 @Override
4242 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4243 final long origId = Binder.clearCallingIdentity();
4244 try {
4245 synchronized (mGlobalLock) {
4246 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4247 "setPictureInPictureParams", token, params);
4248
4249 // Only update the saved args from the args that are set
4250 r.pictureInPictureArgs.copyOnlySet(params);
4251 if (r.inPinnedWindowingMode()) {
4252 // If the activity is already in picture-in-picture, update the pinned stack now
4253 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4254 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004255 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 if (!stack.isAnimatingBoundsToFullscreen()) {
4257 stack.setPictureInPictureAspectRatio(
4258 r.pictureInPictureArgs.getAspectRatio());
4259 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4260 }
4261 }
4262 logPictureInPictureArgs(params);
4263 }
4264 } finally {
4265 Binder.restoreCallingIdentity(origId);
4266 }
4267 }
4268
4269 @Override
4270 public int getMaxNumPictureInPictureActions(IBinder token) {
4271 // Currently, this is a static constant, but later, we may change this to be dependent on
4272 // the context of the activity
4273 return 3;
4274 }
4275
4276 private void logPictureInPictureArgs(PictureInPictureParams params) {
4277 if (params.hasSetActions()) {
4278 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4279 params.getActions().size());
4280 }
4281 if (params.hasSetAspectRatio()) {
4282 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4283 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4284 MetricsLogger.action(lm);
4285 }
4286 }
4287
4288 /**
4289 * Checks the state of the system and the activity associated with the given {@param token} to
4290 * verify that picture-in-picture is supported for that activity.
4291 *
4292 * @return the activity record for the given {@param token} if all the checks pass.
4293 */
4294 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4295 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004296 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004297 throw new IllegalStateException(caller
4298 + ": Device doesn't support picture-in-picture mode.");
4299 }
4300
4301 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4302 if (r == null) {
4303 throw new IllegalStateException(caller
4304 + ": Can't find activity for token=" + token);
4305 }
4306
4307 if (!r.supportsPictureInPicture()) {
4308 throw new IllegalStateException(caller
4309 + ": Current activity does not support picture-in-picture.");
4310 }
4311
4312 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004313 && !mWindowManager.isValidPictureInPictureAspectRatio(
4314 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 final float minAspectRatio = mContext.getResources().getFloat(
4316 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4317 final float maxAspectRatio = mContext.getResources().getFloat(
4318 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4319 throw new IllegalArgumentException(String.format(caller
4320 + ": Aspect ratio is too extreme (must be between %f and %f).",
4321 minAspectRatio, maxAspectRatio));
4322 }
4323
4324 // Truncate the number of actions if necessary
4325 params.truncateActions(getMaxNumPictureInPictureActions(token));
4326
4327 return r;
4328 }
4329
4330 @Override
4331 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004332 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 synchronized (mGlobalLock) {
4334 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4335 if (r == null) {
4336 throw new IllegalArgumentException("Activity does not exist; token="
4337 + activityToken);
4338 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004339 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004340 }
4341 }
4342
4343 @Override
4344 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4345 Rect tempDockedTaskInsetBounds,
4346 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004347 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 long ident = Binder.clearCallingIdentity();
4349 try {
4350 synchronized (mGlobalLock) {
4351 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4352 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4353 PRESERVE_WINDOWS);
4354 }
4355 } finally {
4356 Binder.restoreCallingIdentity(ident);
4357 }
4358 }
4359
4360 @Override
4361 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004362 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 final long ident = Binder.clearCallingIdentity();
4364 try {
4365 synchronized (mGlobalLock) {
4366 mStackSupervisor.setSplitScreenResizing(resizing);
4367 }
4368 } finally {
4369 Binder.restoreCallingIdentity(ident);
4370 }
4371 }
4372
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004373 /**
4374 * Check that we have the features required for VR-related API calls, and throw an exception if
4375 * not.
4376 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004377 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004378 if (!mContext.getPackageManager().hasSystemFeature(
4379 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4380 throw new UnsupportedOperationException("VR mode not supported on this device!");
4381 }
4382 }
4383
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 @Override
4385 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387
4388 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4389
4390 ActivityRecord r;
4391 synchronized (mGlobalLock) {
4392 r = ActivityRecord.isInStackLocked(token);
4393 }
4394
4395 if (r == null) {
4396 throw new IllegalArgumentException();
4397 }
4398
4399 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004400 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 VrManagerInternal.NO_ERROR) {
4402 return err;
4403 }
4404
4405 // Clear the binder calling uid since this path may call moveToTask().
4406 final long callingId = Binder.clearCallingIdentity();
4407 try {
4408 synchronized (mGlobalLock) {
4409 r.requestedVrComponent = (enabled) ? packageName : null;
4410
4411 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004412 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004413 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 }
4415 return 0;
4416 }
4417 } finally {
4418 Binder.restoreCallingIdentity(callingId);
4419 }
4420 }
4421
4422 @Override
4423 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4424 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4425 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004426 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4428 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4429 }
Louis Changcdec0802019-11-11 11:45:07 +08004430 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 || activity.voiceSession != null) {
4432 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4433 return;
4434 }
4435 if (activity.pendingVoiceInteractionStart) {
4436 Slog.w(TAG, "Pending start of voice interaction already.");
4437 return;
4438 }
4439 activity.pendingVoiceInteractionStart = true;
4440 }
4441 LocalServices.getService(VoiceInteractionManagerInternal.class)
4442 .startLocalVoiceInteraction(callingActivity, options);
4443 }
4444
4445 @Override
4446 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4447 LocalServices.getService(VoiceInteractionManagerInternal.class)
4448 .stopLocalVoiceInteraction(callingActivity);
4449 }
4450
4451 @Override
4452 public boolean supportsLocalVoiceInteraction() {
4453 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4454 .supportsLocalVoiceInteraction();
4455 }
4456
4457 /** Notifies all listeners when the pinned stack animation starts. */
4458 @Override
4459 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004460 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 }
4462
4463 /** Notifies all listeners when the pinned stack animation ends. */
4464 @Override
4465 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004466 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004467 }
4468
4469 @Override
4470 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004471 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 final long ident = Binder.clearCallingIdentity();
4473 try {
4474 synchronized (mGlobalLock) {
4475 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4476 }
4477 } finally {
4478 Binder.restoreCallingIdentity(ident);
4479 }
4480 }
4481
4482 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004483 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004484 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485
4486 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004487 if (mWindowManager == null) {
4488 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4489 return false;
4490 }
4491
4492 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004494 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 }
4496
Riddle Hsua0022cd2019-09-09 21:12:41 +08004497 mH.sendMessage(PooledLambda.obtainMessage(
4498 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4499 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004500
4501 final long origId = Binder.clearCallingIdentity();
4502 try {
4503 if (values != null) {
4504 Settings.System.clearConfiguration(values);
4505 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004506 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 UserHandle.USER_NULL, false /* deferResume */,
4508 mTmpUpdateConfigurationResult);
4509 return mTmpUpdateConfigurationResult.changes != 0;
4510 } finally {
4511 Binder.restoreCallingIdentity(origId);
4512 }
4513 }
4514 }
4515
4516 @Override
4517 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4518 CharSequence message) {
4519 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004520 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4522 }
4523 final long callingId = Binder.clearCallingIdentity();
4524 try {
4525 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004526 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004527 }
4528 } finally {
4529 Binder.restoreCallingIdentity(callingId);
4530 }
4531 }
4532
4533 @Override
4534 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004535 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004536 "cancelTaskWindowTransition()");
4537 final long ident = Binder.clearCallingIdentity();
4538 try {
4539 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004540 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004541 MATCH_TASK_IN_STACKS_ONLY);
4542 if (task == null) {
4543 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4544 return;
4545 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004546 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 }
4548 } finally {
4549 Binder.restoreCallingIdentity(ident);
4550 }
4551 }
4552
4553 @Override
4554 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004555 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556 final long ident = Binder.clearCallingIdentity();
4557 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004558 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 } finally {
4560 Binder.restoreCallingIdentity(ident);
4561 }
4562 }
4563
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004564 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4565 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004566 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004567 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004568 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004569 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4570 if (task == null) {
4571 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4572 return null;
4573 }
4574 }
4575 // Don't call this while holding the lock as this operation might hit the disk.
4576 return task.getSnapshot(reducedResolution, restoreFromDisk);
4577 }
4578
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004579 @Override
4580 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4581 synchronized (mGlobalLock) {
4582 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4583 if (r == null) {
4584 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4585 + token);
4586 return;
4587 }
4588 final long origId = Binder.clearCallingIdentity();
4589 try {
4590 r.setDisablePreviewScreenshots(disable);
4591 } finally {
4592 Binder.restoreCallingIdentity(origId);
4593 }
4594 }
4595 }
4596
Riddle Hsu440f88b2019-11-06 22:17:35 +08004597 @Override
4598 public void invalidateHomeTaskSnapshot(IBinder token) {
4599 synchronized (mGlobalLock) {
4600 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4601 if (r == null || !r.isActivityTypeHome()) {
4602 return;
4603 }
4604 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4605 }
4606 }
4607
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004608 /** Return the user id of the last resumed activity. */
4609 @Override
4610 public @UserIdInt
4611 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004612 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4614 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004615 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004616 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004618 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004619 }
4620 }
4621
4622 @Override
4623 public void updateLockTaskFeatures(int userId, int flags) {
4624 final int callingUid = Binder.getCallingUid();
4625 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004626 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004627 "updateLockTaskFeatures()");
4628 }
4629 synchronized (mGlobalLock) {
4630 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4631 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004632 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 }
4634 }
4635
4636 @Override
4637 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4638 synchronized (mGlobalLock) {
4639 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4640 if (r == null) {
4641 return;
4642 }
4643 final long origId = Binder.clearCallingIdentity();
4644 try {
4645 r.setShowWhenLocked(showWhenLocked);
4646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650 }
4651
4652 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004653 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4654 synchronized (mGlobalLock) {
4655 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4656 if (r == null) {
4657 return;
4658 }
4659 final long origId = Binder.clearCallingIdentity();
4660 try {
4661 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4662 } finally {
4663 Binder.restoreCallingIdentity(origId);
4664 }
4665 }
4666 }
4667
4668 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004669 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4670 synchronized (mGlobalLock) {
4671 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4672 if (r == null) {
4673 return;
4674 }
4675 final long origId = Binder.clearCallingIdentity();
4676 try {
4677 r.setTurnScreenOn(turnScreenOn);
4678 } finally {
4679 Binder.restoreCallingIdentity(origId);
4680 }
4681 }
4682 }
4683
4684 @Override
4685 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004686 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004687 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004688 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 synchronized (mGlobalLock) {
4690 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4691 if (r == null) {
4692 return;
4693 }
4694 final long origId = Binder.clearCallingIdentity();
4695 try {
4696 r.registerRemoteAnimations(definition);
4697 } finally {
4698 Binder.restoreCallingIdentity(origId);
4699 }
4700 }
4701 }
4702
4703 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004704 public void unregisterRemoteAnimations(IBinder token) {
4705 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4706 "unregisterRemoteAnimations");
4707 synchronized (mGlobalLock) {
4708 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4709 if (r == null) {
4710 return;
4711 }
4712 final long origId = Binder.clearCallingIdentity();
4713 try {
4714 r.unregisterRemoteAnimations();
4715 } finally {
4716 Binder.restoreCallingIdentity(origId);
4717 }
4718 }
4719 }
4720
4721 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004722 public void registerRemoteAnimationForNextActivityStart(String packageName,
4723 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004724 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004725 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004726 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004727 synchronized (mGlobalLock) {
4728 final long origId = Binder.clearCallingIdentity();
4729 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004730 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004731 packageName, adapter);
4732 } finally {
4733 Binder.restoreCallingIdentity(origId);
4734 }
4735 }
4736 }
4737
Evan Rosky966759f2019-01-15 10:33:58 -08004738 @Override
4739 public void registerRemoteAnimationsForDisplay(int displayId,
4740 RemoteAnimationDefinition definition) {
4741 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4742 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004743 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004744 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004745 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004746 if (display == null) {
4747 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4748 return;
4749 }
4750 final long origId = Binder.clearCallingIdentity();
4751 try {
4752 display.mDisplayContent.registerRemoteAnimations(definition);
4753 } finally {
4754 Binder.restoreCallingIdentity(origId);
4755 }
4756 }
4757 }
4758
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004759 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4760 @Override
4761 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4762 synchronized (mGlobalLock) {
4763 final long origId = Binder.clearCallingIdentity();
4764 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004765 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004766 } finally {
4767 Binder.restoreCallingIdentity(origId);
4768 }
4769 }
4770 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004771
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004772 @Override
4773 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004774 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004776 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004777 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004778 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004779 }
4780 }
4781
4782 @Override
4783 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 != PERMISSION_GRANTED) {
4786 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4787 + Binder.getCallingPid()
4788 + ", uid=" + Binder.getCallingUid()
4789 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4790 Slog.w(TAG, msg);
4791 throw new SecurityException(msg);
4792 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004793 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004795 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004796 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004797 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004798 }
4799 }
4800
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004801 @Override
4802 public void stopAppSwitches() {
4803 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4804 synchronized (mGlobalLock) {
4805 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004806 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004807 mDidAppSwitch = false;
4808 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4809 }
4810 }
4811
4812 @Override
4813 public void resumeAppSwitches() {
4814 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4815 synchronized (mGlobalLock) {
4816 // Note that we don't execute any pending app switches... we will
4817 // let those wait until either the timeout, or the next start
4818 // activity request.
4819 mAppSwitchesAllowedTime = 0;
4820 }
4821 }
4822
Ricky Wai906af482019-06-03 17:25:28 +01004823 long getLastStopAppSwitchesTime() {
4824 return mLastStopAppSwitchesTime;
4825 }
4826
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004827 void onStartActivitySetDidAppSwitch() {
4828 if (mDidAppSwitch) {
4829 // This is the second allowed switch since we stopped switches, so now just generally
4830 // allow switches. Use case:
4831 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4832 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4833 // anyone to switch again).
4834 mAppSwitchesAllowedTime = 0;
4835 } else {
4836 mDidAppSwitch = true;
4837 }
4838 }
4839
4840 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004841 boolean shouldDisableNonVrUiLocked() {
4842 return mVrController.shouldDisableNonVrUiLocked();
4843 }
4844
Wale Ogunwale53783742018-09-16 10:21:51 -07004845 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004846 // 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 +00004847 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004848 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004849 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4850 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004851 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004852 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004853 }
4854 mH.post(() -> {
4855 if (!mVrController.onVrModeChanged(r)) {
4856 return;
4857 }
4858 synchronized (mGlobalLock) {
4859 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4860 mWindowManager.disableNonVrUi(disableNonVrUi);
4861 if (disableNonVrUi) {
4862 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4863 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004864 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004865 }
4866 }
4867 });
4868 }
4869
Wale Ogunwale53783742018-09-16 10:21:51 -07004870 @Override
4871 public int getPackageScreenCompatMode(String packageName) {
4872 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4873 synchronized (mGlobalLock) {
4874 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4875 }
4876 }
4877
4878 @Override
4879 public void setPackageScreenCompatMode(String packageName, int mode) {
4880 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4881 "setPackageScreenCompatMode");
4882 synchronized (mGlobalLock) {
4883 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4884 }
4885 }
4886
4887 @Override
4888 public boolean getPackageAskScreenCompat(String packageName) {
4889 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4890 synchronized (mGlobalLock) {
4891 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4892 }
4893 }
4894
4895 @Override
4896 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4897 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4898 "setPackageAskScreenCompat");
4899 synchronized (mGlobalLock) {
4900 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4901 }
4902 }
4903
Wale Ogunwale64258362018-10-16 15:13:37 -07004904 public static String relaunchReasonToString(int relaunchReason) {
4905 switch (relaunchReason) {
4906 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4907 return "window_resize";
4908 case RELAUNCH_REASON_FREE_RESIZE:
4909 return "free_resize";
4910 default:
4911 return null;
4912 }
4913 }
4914
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004915 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004916 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004917 }
4918
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004919 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004920 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004921 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4922 }
4923
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004924 boolean isKeyguardLocked() {
4925 return mKeyguardController.isKeyguardLocked();
4926 }
4927
Garfield Tan01548632018-11-27 10:15:48 -08004928 /**
4929 * Clears launch params for the given package.
4930 * @param packageNames the names of the packages of which the launch params are to be cleared
4931 */
4932 @Override
4933 public void clearLaunchParamsForPackages(List<String> packageNames) {
4934 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4935 "clearLaunchParamsForPackages");
4936 synchronized (mGlobalLock) {
4937 for (int i = 0; i < packageNames.size(); ++i) {
4938 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4939 }
4940 }
4941 }
4942
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004943 /**
4944 * Makes the display with the given id a single task instance display. I.e the display can only
4945 * contain one task.
4946 */
4947 @Override
4948 public void setDisplayToSingleTaskInstance(int displayId) {
4949 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4950 "setDisplayToSingleTaskInstance");
4951 final long origId = Binder.clearCallingIdentity();
4952 try {
Louis Chang677921f2019-12-06 16:44:24 +08004953 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004954 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004955 if (display != null) {
4956 display.setDisplayToSingleTaskInstance();
4957 }
4958 } finally {
4959 Binder.restoreCallingIdentity(origId);
4960 }
4961 }
4962
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004963 /**
4964 * Requests that an activity should enter picture-in-picture mode if possible.
4965 */
4966 @Override
4967 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4968 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4969 "requestPictureInPictureMode");
4970 final long origId = Binder.clearCallingIdentity();
4971 try {
4972 synchronized (mGlobalLock) {
4973 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4974 if (activity == null) {
4975 return;
4976 }
4977
4978 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4979 "requestPictureInPictureMode", /* beforeStopping */ false);
4980 if (!canEnterPictureInPicture) {
4981 throw new IllegalStateException(
4982 "Requested PIP on an activity that doesn't support it");
4983 }
4984
4985 try {
4986 final ClientTransaction transaction = ClientTransaction.obtain(
4987 activity.app.getThread(),
4988 activity.token);
4989 transaction.addCallback(EnterPipRequestedItem.obtain());
4990 getLifecycleManager().scheduleTransaction(transaction);
4991 } catch (Exception e) {
4992 Slog.w(TAG, "Failed to send enter pip requested item: "
4993 + activity.intent.getComponent(), e);
4994 }
4995 }
4996 } finally {
4997 Binder.restoreCallingIdentity(origId);
4998 }
4999 }
5000
Wale Ogunwale31913b52018-10-13 08:29:31 -07005001 void dumpLastANRLocked(PrintWriter pw) {
5002 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5003 if (mLastANRState == null) {
5004 pw.println(" <no ANR has occurred since boot>");
5005 } else {
5006 pw.println(mLastANRState);
5007 }
5008 }
5009
5010 void dumpLastANRTracesLocked(PrintWriter pw) {
5011 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5012
5013 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5014 if (ArrayUtils.isEmpty(files)) {
5015 pw.println(" <no ANR has occurred since boot>");
5016 return;
5017 }
5018 // Find the latest file.
5019 File latest = null;
5020 for (File f : files) {
5021 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5022 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005023 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005024 }
5025 pw.print("File: ");
5026 pw.print(latest.getName());
5027 pw.println();
5028 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5029 String line;
5030 while ((line = in.readLine()) != null) {
5031 pw.println(line);
5032 }
5033 } catch (IOException e) {
5034 pw.print("Unable to read: ");
5035 pw.print(e);
5036 pw.println();
5037 }
5038 }
5039
5040 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5041 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5042 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5043 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5044 }
5045
5046 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5047 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5048 pw.println(header);
5049
Louis Chang149d5c82019-12-30 09:47:39 +08005050 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005051 dumpPackage);
5052 boolean needSep = printedAnything;
5053
5054 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005055 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005056 " ResumedActivity: ");
5057 if (printed) {
5058 printedAnything = true;
5059 needSep = false;
5060 }
5061
5062 if (dumpPackage == null) {
5063 if (needSep) {
5064 pw.println();
5065 }
5066 printedAnything = true;
5067 mStackSupervisor.dump(pw, " ");
5068 }
5069
5070 if (!printedAnything) {
5071 pw.println(" (nothing)");
5072 }
5073 }
5074
5075 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005076 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005077 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005078 pw.println(" ");
5079 }
5080
5081 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5082 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5083 getActivityStartController().dump(pw, "", dumpPackage);
5084 }
5085
5086 /**
5087 * There are three things that cmd can be:
5088 * - a flattened component name that matches an existing activity
5089 * - the cmd arg isn't the flattened component name of an existing activity:
5090 * dump all activity whose component contains the cmd as a substring
5091 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005092 * <p>
5093 * The caller should not hold lock when calling this method because it will wait for the
5094 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005095 *
5096 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5097 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5098 */
5099 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5100 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5101 ArrayList<ActivityRecord> activities;
5102
5103 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005104 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005105 dumpFocusedStackOnly);
5106 }
5107
5108 if (activities.size() <= 0) {
5109 return false;
5110 }
5111
5112 String[] newArgs = new String[args.length - opti];
5113 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5114
Louis Changcdec0802019-11-11 11:45:07 +08005115 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005116 boolean needSep = false;
5117 for (int i = activities.size() - 1; i >= 0; i--) {
5118 ActivityRecord r = activities.get(i);
5119 if (needSep) {
5120 pw.println();
5121 }
5122 needSep = true;
5123 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005124 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005125 if (lastTask != task) {
5126 lastTask = task;
5127 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005128 pw.print(" id="); pw.print(lastTask.mTaskId);
5129 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005130 if (dumpAll) {
5131 lastTask.dump(pw, " ");
5132 }
5133 }
5134 }
5135 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5136 }
5137 return true;
5138 }
5139
5140 /**
5141 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5142 * there is a thread associated with the activity.
5143 */
5144 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5145 final ActivityRecord r, String[] args, boolean dumpAll) {
5146 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005147 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005148 synchronized (mGlobalLock) {
5149 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5150 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5151 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005152 if (r.hasProcess()) {
5153 pw.println(r.app.getPid());
5154 appThread = r.app.getThread();
5155 } else {
5156 pw.println("(not running)");
5157 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005158 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005159 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005160 }
5161 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005162 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005163 // flush anything that is already in the PrintWriter since the thread is going
5164 // to write to the file descriptor directly
5165 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005166 try (TransferPipe tp = new TransferPipe()) {
5167 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5168 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005169 } catch (IOException e) {
5170 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5171 } catch (RemoteException e) {
5172 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5173 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005174 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005175 }
5176
sanryhuang498e77e2018-12-06 14:57:01 +08005177 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5178 boolean testPssMode) {
5179 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5180 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5181 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005182 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005183 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5184 st.toString());
5185 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005186 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5187 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5188 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005189 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5190 testPssMode);
5191 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005192 }
5193
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194 int getCurrentUserId() {
5195 return mAmInternal.getCurrentUserId();
5196 }
5197
5198 private void enforceNotIsolatedCaller(String caller) {
5199 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5200 throw new SecurityException("Isolated process not allowed to call " + caller);
5201 }
5202 }
5203
Wale Ogunwalef6733932018-06-27 05:14:34 -07005204 public Configuration getConfiguration() {
5205 Configuration ci;
5206 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005207 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005208 ci.userSetLocale = false;
5209 }
5210 return ci;
5211 }
5212
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213 /**
5214 * Current global configuration information. Contains general settings for the entire system,
5215 * also corresponds to the merged configuration of the default display.
5216 */
5217 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005218 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005219 // while initializing process record for system, see {@link
5220 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005221 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005222 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223 }
5224
5225 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5226 boolean initLocale) {
5227 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5228 }
5229
5230 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5231 boolean initLocale, boolean deferResume) {
5232 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5233 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5234 UserHandle.USER_NULL, deferResume);
5235 }
5236
Wale Ogunwale59507092018-10-29 09:00:30 -07005237 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238 final long origId = Binder.clearCallingIdentity();
5239 try {
5240 synchronized (mGlobalLock) {
5241 updateConfigurationLocked(values, null, false, true, userId,
5242 false /* deferResume */);
5243 }
5244 } finally {
5245 Binder.restoreCallingIdentity(origId);
5246 }
5247 }
5248
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5250 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5251 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5252 deferResume, null /* result */);
5253 }
5254
5255 /**
5256 * Do either or both things: (1) change the current configuration, and (2)
5257 * make sure the given activity is running with the (now) current
5258 * configuration. Returns true if the activity has been left running, or
5259 * false if <var>starting</var> is being destroyed to match the new
5260 * configuration.
5261 *
5262 * @param userId is only used when persistent parameter is set to true to persist configuration
5263 * for that particular user
5264 */
5265 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5266 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5267 ActivityTaskManagerService.UpdateConfigurationResult result) {
5268 int changes = 0;
5269 boolean kept = true;
5270
Riddle Hsua0022cd2019-09-09 21:12:41 +08005271 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005272 try {
5273 if (values != null) {
5274 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5275 deferResume);
5276 }
5277
5278 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5279 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005280 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005281 }
5282
5283 if (result != null) {
5284 result.changes = changes;
5285 result.activityRelaunched = !kept;
5286 }
5287 return kept;
5288 }
5289
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005290 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005291 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005293
Louis Chang677921f2019-12-06 16:44:24 +08005294 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005295 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005296
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005297 mTempConfig.setTo(getGlobalConfiguration());
5298 final int changes = mTempConfig.updateFrom(values);
5299 if (changes == 0) {
5300 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5301 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5302 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5303 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005304 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005305 return 0;
5306 }
5307
5308 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5309 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005310 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005311 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5312 values.colorMode,
5313 values.densityDpi,
5314 values.fontScale,
5315 values.hardKeyboardHidden,
5316 values.keyboard,
5317 values.keyboardHidden,
5318 values.mcc,
5319 values.mnc,
5320 values.navigation,
5321 values.navigationHidden,
5322 values.orientation,
5323 values.screenHeightDp,
5324 values.screenLayout,
5325 values.screenWidthDp,
5326 values.smallestScreenWidthDp,
5327 values.touchscreen,
5328 values.uiMode);
5329
5330
5331 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5332 final LocaleList locales = values.getLocales();
5333 int bestLocaleIndex = 0;
5334 if (locales.size() > 1) {
5335 if (mSupportedSystemLocales == null) {
5336 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5337 }
5338 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5339 }
5340 SystemProperties.set("persist.sys.locale",
5341 locales.get(bestLocaleIndex).toLanguageTag());
5342 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005343
5344 final Message m = PooledLambda.obtainMessage(
5345 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5346 locales.get(bestLocaleIndex));
5347 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005348 }
5349
Yunfan Chen75157d72018-07-27 14:47:21 +09005350 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
5352 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005353 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005354
5355 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5356 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005357 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005358
5359 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005361
5362 AttributeCache ac = AttributeCache.instance();
5363 if (ac != null) {
5364 ac.updateConfiguration(mTempConfig);
5365 }
5366
5367 // Make sure all resources in our process are updated right now, so that anyone who is going
5368 // to retrieve resource values after we return will be sure to get the new ones. This is
5369 // especially important during boot, where the first config change needs to guarantee all
5370 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005371 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005372
5373 // We need another copy of global config because we're scheduling some calls instead of
5374 // running them in place. We need to be sure that object we send will be handled unchanged.
5375 final Configuration configCopy = new Configuration(mTempConfig);
5376 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005377 final Message msg = PooledLambda.obtainMessage(
5378 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5379 this, userId, configCopy);
5380 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005381 }
5382
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005383 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5384 for (int i = pidMap.size() - 1; i >= 0; i--) {
5385 final int pid = pidMap.keyAt(i);
5386 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005387 if (DEBUG_CONFIGURATION) {
5388 Slog.v(TAG_CONFIGURATION, "Update process config of "
5389 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005390 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005391 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005392 }
5393
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005394 final Message msg = PooledLambda.obtainMessage(
5395 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5396 mAmInternal, changes, initLocale);
5397 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005398
5399 // Override configuration of the default display duplicates global config, so we need to
5400 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005401 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005402 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005403
5404 return changes;
5405 }
5406
Riddle Hsua0022cd2019-09-09 21:12:41 +08005407 /** @see WindowSurfacePlacer#deferLayout */
5408 void deferWindowLayout() {
5409 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5410 // Reset the reasons at the first entrance because we only care about the changes in the
5411 // deferred scope.
5412 mLayoutReasons = 0;
5413 }
5414
5415 mWindowManager.mWindowPlacerLocked.deferLayout();
5416 }
5417
5418 /** @see WindowSurfacePlacer#continueLayout */
5419 void continueWindowLayout() {
5420 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5421 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5422 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5423 }
5424 }
5425
5426 /**
5427 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5428 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5429 * defer count is gone.
5430 */
5431 void addWindowLayoutReasons(@LayoutReason int reasons) {
5432 mLayoutReasons |= reasons;
5433 }
5434
Wale Ogunwalef6733932018-06-27 05:14:34 -07005435 private void updateEventDispatchingLocked(boolean booted) {
5436 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5437 }
5438
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005439 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5440 final ContentResolver resolver = mContext.getContentResolver();
5441 Settings.System.putConfigurationForUser(resolver, config, userId);
5442 }
5443
5444 private void sendLocaleToMountDaemonMsg(Locale l) {
5445 try {
5446 IBinder service = ServiceManager.getService("mount");
5447 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5448 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5449 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5450 } catch (RemoteException e) {
5451 Log.e(TAG, "Error storing locale for decryption UI", e);
5452 }
5453 }
5454
Alison Cichowlas3e340502018-08-07 17:15:01 -04005455 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5456 mStartActivitySources.remove(permissionToken);
5457 mExpiredStartAsCallerTokens.add(permissionToken);
5458 }
5459
5460 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5461 mExpiredStartAsCallerTokens.remove(permissionToken);
5462 }
5463
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005464 boolean isActivityStartsLoggingEnabled() {
5465 return mAmInternal.isActivityStartsLoggingEnabled();
5466 }
5467
Michal Karpinski8596ded2018-11-14 14:43:48 +00005468 boolean isBackgroundActivityStartsEnabled() {
5469 return mAmInternal.isBackgroundActivityStartsEnabled();
5470 }
5471
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005473 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005474 mWindowManager.enableScreenAfterBoot();
5475
5476 synchronized (mGlobalLock) {
5477 updateEventDispatchingLocked(booted);
5478 }
5479 }
5480
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005481 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5482 if (r == null || !r.hasProcess()) {
5483 return KEY_DISPATCHING_TIMEOUT_MS;
5484 }
5485 return getInputDispatchingTimeoutLocked(r.app);
5486 }
5487
5488 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005489 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005490 }
5491
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 /**
5493 * Decide based on the configuration whether we should show the ANR,
5494 * crash, etc dialogs. The idea is that if there is no affordance to
5495 * press the on-screen buttons, or the user experience would be more
5496 * greatly impacted than the crash itself, we shouldn't show the dialog.
5497 *
5498 * A thought: SystemUI might also want to get told about this, the Power
5499 * dialog / global actions also might want different behaviors.
5500 */
5501 private void updateShouldShowDialogsLocked(Configuration config) {
5502 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5503 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5504 && config.navigation == Configuration.NAVIGATION_NONAV);
5505 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5506 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5507 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5508 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5509 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5510 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5511 HIDE_ERROR_DIALOGS, 0) != 0;
5512 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5513 }
5514
5515 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5516 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5517 FONT_SCALE, 1.0f, userId);
5518
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005519 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005520 if (getGlobalConfiguration().fontScale == scaleFactor) {
5521 return;
5522 }
5523
5524 final Configuration configuration
5525 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5526 configuration.fontScale = scaleFactor;
5527 updatePersistentConfiguration(configuration, userId);
5528 }
5529 }
5530
5531 // Actually is sleeping or shutting down or whatever else in the future
5532 // is an inactive state.
5533 boolean isSleepingOrShuttingDownLocked() {
5534 return isSleepingLocked() || mShuttingDown;
5535 }
5536
5537 boolean isSleepingLocked() {
5538 return mSleeping;
5539 }
5540
Riddle Hsu16567132018-08-16 21:37:47 +08005541 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005542 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005543 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 if (task.isActivityTypeStandard()) {
5545 if (mCurAppTimeTracker != r.appTimeTracker) {
5546 // We are switching app tracking. Complete the current one.
5547 if (mCurAppTimeTracker != null) {
5548 mCurAppTimeTracker.stop();
5549 mH.obtainMessage(
5550 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005551 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005552 mCurAppTimeTracker = null;
5553 }
5554 if (r.appTimeTracker != null) {
5555 mCurAppTimeTracker = r.appTimeTracker;
5556 startTimeTrackingFocusedActivityLocked();
5557 }
5558 } else {
5559 startTimeTrackingFocusedActivityLocked();
5560 }
5561 } else {
5562 r.appTimeTracker = null;
5563 }
5564 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5565 // TODO: Probably not, because we don't want to resume voice on switching
5566 // back to this activity
5567 if (task.voiceInteractor != null) {
5568 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5569 } else {
5570 finishRunningVoiceLocked();
5571
5572 if (mLastResumedActivity != null) {
5573 final IVoiceInteractionSession session;
5574
Louis Changcdec0802019-11-11 11:45:07 +08005575 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005576 if (lastResumedActivityTask != null
5577 && lastResumedActivityTask.voiceSession != null) {
5578 session = lastResumedActivityTask.voiceSession;
5579 } else {
5580 session = mLastResumedActivity.voiceSession;
5581 }
5582
5583 if (session != null) {
5584 // We had been in a voice interaction session, but now focused has
5585 // move to something different. Just finish the session, we can't
5586 // return to it and retain the proper state and synchronization with
5587 // the voice interaction service.
5588 finishVoiceTask(session);
5589 }
5590 }
5591 }
5592
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005593 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5594 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005595 }
5596 updateResumedAppTrace(r);
5597 mLastResumedActivity = r;
5598
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005599 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600
5601 applyUpdateLockStateLocked(r);
5602 applyUpdateVrModeLocked(r);
5603
Jeff Changd136e772019-11-05 20:33:52 +08005604 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005605 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005606 r == null ? "NULL" : r.shortComponentName,
5607 reason);
5608 }
5609
5610 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5611 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005612 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005613 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005614 updateSleepIfNeededLocked();
5615 return token;
5616 }
5617 }
5618
5619 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005620 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005621 final boolean wasSleeping = mSleeping;
5622 boolean updateOomAdj = false;
5623
5624 if (!shouldSleep) {
5625 // If wasSleeping is true, we need to wake up activity manager state from when
5626 // we started sleeping. In either case, we need to apply the sleep tokens, which
5627 // will wake up stacks or put them to sleep as appropriate.
5628 if (wasSleeping) {
5629 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005630 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5631 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005632 startTimeTrackingFocusedActivityLocked();
5633 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005634 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005635 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5636 }
Louis Chang149d5c82019-12-30 09:47:39 +08005637 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005638 if (wasSleeping) {
5639 updateOomAdj = true;
5640 }
5641 } else if (!mSleeping && shouldSleep) {
5642 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005643 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5644 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005645 if (mCurAppTimeTracker != null) {
5646 mCurAppTimeTracker.stop();
5647 }
5648 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005649 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005650 mStackSupervisor.goingToSleepLocked();
5651 updateResumedAppTrace(null /* resumed */);
5652 updateOomAdj = true;
5653 }
5654 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005655 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005656 }
5657 }
5658
5659 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005660 mH.removeCallbacks(mUpdateOomAdjRunnable);
5661 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005662 }
5663
Wale Ogunwale53783742018-09-16 10:21:51 -07005664 void updateCpuStats() {
5665 mH.post(mAmInternal::updateCpuStats);
5666 }
5667
Hui Yu03d12402018-12-06 18:00:37 -08005668 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5669 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005670 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5671 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005672 mH.sendMessage(m);
5673 }
5674
Hui Yu03d12402018-12-06 18:00:37 -08005675 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005676 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005677 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005678 if (task != null) {
5679 final ActivityRecord rootActivity = task.getRootActivity();
5680 if (rootActivity != null) {
5681 taskRoot = rootActivity.mActivityComponent;
5682 }
5683 }
5684
Hui Yu03d12402018-12-06 18:00:37 -08005685 final Message m = PooledLambda.obtainMessage(
5686 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005687 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005688 mH.sendMessage(m);
5689 }
5690
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005691 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5692 String hostingType) {
5693 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005694 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5695 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005696 + activity.processName);
5697 }
5698 // Post message to start process to avoid possible deadlock of calling into AMS with the
5699 // ATMS lock held.
5700 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5701 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5702 isTop, hostingType, activity.intent.getComponent());
5703 mH.sendMessage(m);
5704 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005705 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005706 }
5707 }
5708
Wale Ogunwale53783742018-09-16 10:21:51 -07005709 void setBooting(boolean booting) {
5710 mAmInternal.setBooting(booting);
5711 }
5712
5713 boolean isBooting() {
5714 return mAmInternal.isBooting();
5715 }
5716
5717 void setBooted(boolean booted) {
5718 mAmInternal.setBooted(booted);
5719 }
5720
5721 boolean isBooted() {
5722 return mAmInternal.isBooted();
5723 }
5724
5725 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5726 mH.post(() -> {
5727 if (finishBooting) {
5728 mAmInternal.finishBooting();
5729 }
5730 if (enableScreen) {
5731 mInternal.enableScreenAfterBoot(isBooted());
5732 }
5733 });
5734 }
5735
5736 void setHeavyWeightProcess(ActivityRecord root) {
5737 mHeavyWeightProcess = root.app;
5738 final Message m = PooledLambda.obtainMessage(
5739 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005740 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005741 mH.sendMessage(m);
5742 }
5743
5744 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5745 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5746 return;
5747 }
5748
5749 mHeavyWeightProcess = null;
5750 final Message m = PooledLambda.obtainMessage(
5751 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5752 proc.mUserId);
5753 mH.sendMessage(m);
5754 }
5755
5756 private void cancelHeavyWeightProcessNotification(int userId) {
5757 final INotificationManager inm = NotificationManager.getService();
5758 if (inm == null) {
5759 return;
5760 }
5761 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005762 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005763 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5764 } catch (RuntimeException e) {
5765 Slog.w(TAG, "Error canceling notification for service", e);
5766 } catch (RemoteException e) {
5767 }
5768
5769 }
5770
5771 private void postHeavyWeightProcessNotification(
5772 WindowProcessController proc, Intent intent, int userId) {
5773 if (proc == null) {
5774 return;
5775 }
5776
5777 final INotificationManager inm = NotificationManager.getService();
5778 if (inm == null) {
5779 return;
5780 }
5781
5782 try {
5783 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5784 String text = mContext.getString(R.string.heavy_weight_notification,
5785 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5786 Notification notification =
5787 new Notification.Builder(context,
5788 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5789 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5790 .setWhen(0)
5791 .setOngoing(true)
5792 .setTicker(text)
5793 .setColor(mContext.getColor(
5794 com.android.internal.R.color.system_notification_accent_color))
5795 .setContentTitle(text)
5796 .setContentText(
5797 mContext.getText(R.string.heavy_weight_notification_detail))
5798 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5799 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5800 new UserHandle(userId)))
5801 .build();
5802 try {
5803 inm.enqueueNotificationWithTag("android", "android", null,
5804 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5805 } catch (RuntimeException e) {
5806 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5807 } catch (RemoteException e) {
5808 }
5809 } catch (PackageManager.NameNotFoundException e) {
5810 Slog.w(TAG, "Unable to create context for heavy notification", e);
5811 }
5812
5813 }
5814
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005815 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5816 IBinder token, String resultWho, int requestCode, Intent[] intents,
5817 String[] resolvedTypes, int flags, Bundle bOptions) {
5818
5819 ActivityRecord activity = null;
5820 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5821 activity = ActivityRecord.isInStackLocked(token);
5822 if (activity == null) {
5823 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5824 return null;
5825 }
5826 if (activity.finishing) {
5827 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5828 return null;
5829 }
5830 }
5831
5832 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5833 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5834 bOptions);
5835 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5836 if (noCreate) {
5837 return rec;
5838 }
5839 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5840 if (activity.pendingResults == null) {
5841 activity.pendingResults = new HashSet<>();
5842 }
5843 activity.pendingResults.add(rec.ref);
5844 }
5845 return rec;
5846 }
5847
Andrii Kulian52d255c2018-07-13 11:32:19 -07005848 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005849 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005850 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005851 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5852 mCurAppTimeTracker.start(resumedActivity.packageName);
5853 }
5854 }
5855
5856 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5857 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005858 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005859 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5860 }
5861 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005862 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005863 constructResumedTraceName(resumed.packageName), 0);
5864 }
5865 mTracedResumedActivity = resumed;
5866 }
5867
5868 private String constructResumedTraceName(String packageName) {
5869 return "focused app: " + packageName;
5870 }
5871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005872 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005873 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005874 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005875 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005876 // mainStack is null during startup.
5877 if (mainStack != null) {
5878 if (changes != 0 && starting == null) {
5879 // If the configuration changed, and the caller is not already
5880 // in the process of starting an activity, then find the top
5881 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005882 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005883 }
5884
5885 if (starting != null) {
5886 kept = starting.ensureActivityConfiguration(changes,
5887 false /* preserveWindow */);
5888 // And we need to make sure at this point that all other activities
5889 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005890 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005891 !PRESERVE_WINDOWS);
5892 }
5893 }
5894
5895 return kept;
5896 }
5897
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005898 void scheduleAppGcsLocked() {
5899 mH.post(() -> mAmInternal.scheduleAppGcs());
5900 }
5901
Wale Ogunwale53783742018-09-16 10:21:51 -07005902 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5903 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5904 }
5905
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005906 /**
5907 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5908 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5909 * on demand.
5910 */
5911 IPackageManager getPackageManager() {
5912 return AppGlobals.getPackageManager();
5913 }
5914
5915 PackageManagerInternal getPackageManagerInternalLocked() {
5916 if (mPmInternal == null) {
5917 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5918 }
5919 return mPmInternal;
5920 }
5921
Hai Zhangf4da9be2019-05-01 13:46:06 +08005922 PermissionPolicyInternal getPermissionPolicyInternal() {
5923 if (mPermissionPolicyInternal == null) {
5924 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5925 }
5926 return mPermissionPolicyInternal;
5927 }
5928
Wale Ogunwale008163e2018-07-23 23:11:08 -07005929 AppWarnings getAppWarningsLocked() {
5930 return mAppWarnings;
5931 }
5932
Wale Ogunwale214f3482018-10-04 11:00:47 -07005933 Intent getHomeIntent() {
5934 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5935 intent.setComponent(mTopComponent);
5936 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5937 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5938 intent.addCategory(Intent.CATEGORY_HOME);
5939 }
5940 return intent;
5941 }
5942
Chilun2ef71f72018-11-16 17:57:15 +08005943 /**
5944 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5945 * activities.
5946 *
5947 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5948 * component defined in config_secondaryHomeComponent.
5949 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5950 */
5951 Intent getSecondaryHomeIntent(String preferredPackage) {
5952 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005953 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5954 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5955 if (preferredPackage == null || useSystemProvidedLauncher) {
5956 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005957 final String secondaryHomeComponent = mContext.getResources().getString(
5958 com.android.internal.R.string.config_secondaryHomeComponent);
5959 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5960 } else {
5961 intent.setPackage(preferredPackage);
5962 }
5963 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5964 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5965 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5966 }
5967 return intent;
5968 }
5969
Wale Ogunwale214f3482018-10-04 11:00:47 -07005970 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5971 if (info == null) return null;
5972 ApplicationInfo newInfo = new ApplicationInfo(info);
5973 newInfo.initForUser(userId);
5974 return newInfo;
5975 }
5976
Wale Ogunwale9c103022018-10-18 07:44:54 -07005977 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005978 if (uid == SYSTEM_UID) {
5979 // The system gets to run in any process. If there are multiple processes with the same
5980 // uid, just pick the first (this should never happen).
5981 final SparseArray<WindowProcessController> procs =
5982 mProcessNames.getMap().get(processName);
5983 if (procs == null) return null;
5984 final int procCount = procs.size();
5985 for (int i = 0; i < procCount; i++) {
5986 final int procUid = procs.keyAt(i);
5987 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5988 // Don't use an app process or different user process for system component.
5989 continue;
5990 }
5991 return procs.valueAt(i);
5992 }
5993 }
5994
5995 return mProcessNames.get(processName, uid);
5996 }
5997
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005998 WindowProcessController getProcessController(IApplicationThread thread) {
5999 if (thread == null) {
6000 return null;
6001 }
6002
6003 final IBinder threadBinder = thread.asBinder();
6004 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6005 for (int i = pmap.size()-1; i >= 0; i--) {
6006 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6007 for (int j = procs.size() - 1; j >= 0; j--) {
6008 final WindowProcessController proc = procs.valueAt(j);
6009 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6010 return proc;
6011 }
6012 }
6013 }
6014
6015 return null;
6016 }
6017
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006018 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006019 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006020 if (proc == null) return null;
6021 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6022 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006023 }
6024 return null;
6025 }
6026
Riddle Hsua0536432019-02-16 00:38:59 +08006027 int getUidState(int uid) {
6028 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006029 }
6030
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006031 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006032 // A uid is considered to be foreground if it has a visible non-toast window.
6033 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006034 }
6035
Ricky Wai96f5c352019-04-10 18:40:17 +01006036 boolean isDeviceOwner(int uid) {
6037 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006038 }
6039
Ricky Wai96f5c352019-04-10 18:40:17 +01006040 void setDeviceOwnerUid(int uid) {
6041 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006042 }
6043
Wale Ogunwale9de19442018-10-18 19:05:03 -07006044 /**
6045 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6046 * the whitelist
6047 */
6048 String getPendingTempWhitelistTagForUidLocked(int uid) {
6049 return mPendingTempWhitelist.get(uid);
6050 }
6051
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006052 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6053 if (true || Build.IS_USER) {
6054 return;
6055 }
6056
6057 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6058 StrictMode.allowThreadDiskWrites();
6059 try {
6060 File tracesDir = new File("/data/anr");
6061 File tracesFile = null;
6062 try {
6063 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6064
6065 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006066 String timeString =
6067 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6068 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006069 sb.append(": ");
6070 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6071 sb.append(" since ");
6072 sb.append(msg);
6073 FileOutputStream fos = new FileOutputStream(tracesFile);
6074 fos.write(sb.toString().getBytes());
6075 if (app == null) {
6076 fos.write("\n*** No application process!".getBytes());
6077 }
6078 fos.close();
6079 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6080 } catch (IOException e) {
6081 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6082 return;
6083 }
6084
6085 if (app != null && app.getPid() > 0) {
6086 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6087 firstPids.add(app.getPid());
6088 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6089 }
6090
6091 File lastTracesFile = null;
6092 File curTracesFile = null;
6093 for (int i=9; i>=0; i--) {
6094 String name = String.format(Locale.US, "slow%02d.txt", i);
6095 curTracesFile = new File(tracesDir, name);
6096 if (curTracesFile.exists()) {
6097 if (lastTracesFile != null) {
6098 curTracesFile.renameTo(lastTracesFile);
6099 } else {
6100 curTracesFile.delete();
6101 }
6102 }
6103 lastTracesFile = curTracesFile;
6104 }
6105 tracesFile.renameTo(curTracesFile);
6106 } finally {
6107 StrictMode.setThreadPolicy(oldPolicy);
6108 }
6109 }
6110
Michal Karpinskida34cd42019-04-02 19:46:52 +01006111 boolean isAssociatedCompanionApp(int userId, int uid) {
6112 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6113 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006114 return false;
6115 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006116 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006117 }
6118
Issei Suzuki734bc942019-06-05 13:59:52 +02006119 void notifySingleTaskDisplayEmpty(int displayId) {
6120 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6121 }
6122
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006123 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006124 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006125
6126
Wale Ogunwale98875612018-10-12 07:53:02 -07006127 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6128 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006129
Riddle Hsud93a6c42018-11-29 21:50:06 +08006130 H(Looper looper) {
6131 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006132 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006133
6134 @Override
6135 public void handleMessage(Message msg) {
6136 switch (msg.what) {
6137 case REPORT_TIME_TRACKER_MSG: {
6138 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6139 tracker.deliverResult(mContext);
6140 } break;
6141 }
6142 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006143 }
6144
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006145 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006146 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006147
6148 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006149 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006150 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006151
6152 @Override
6153 public void handleMessage(Message msg) {
6154 switch (msg.what) {
6155 case DISMISS_DIALOG_UI_MSG: {
6156 final Dialog d = (Dialog) msg.obj;
6157 d.dismiss();
6158 break;
6159 }
6160 }
6161 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006162 }
6163
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 final class LocalService extends ActivityTaskManagerInternal {
6165 @Override
6166 public SleepToken acquireSleepToken(String tag, int displayId) {
6167 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006168 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006169 }
6170
6171 @Override
6172 public ComponentName getHomeActivityForUser(int userId) {
6173 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006174 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006175 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006176 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006177 }
6178 }
6179
6180 @Override
6181 public void onLocalVoiceInteractionStarted(IBinder activity,
6182 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6183 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006184 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006185 }
6186 }
6187
6188 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006189 public void notifySingleTaskDisplayDrawn(int displayId) {
6190 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6191 }
6192
6193 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 public void notifyAppTransitionFinished() {
6195 synchronized (mGlobalLock) {
6196 mStackSupervisor.notifyAppTransitionDone();
6197 }
6198 }
6199
6200 @Override
6201 public void notifyAppTransitionCancelled() {
6202 synchronized (mGlobalLock) {
6203 mStackSupervisor.notifyAppTransitionDone();
6204 }
6205 }
6206
6207 @Override
6208 public List<IBinder> getTopVisibleActivities() {
6209 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006210 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006211 }
6212 }
6213
6214 @Override
6215 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6216 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006217 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006218 }
6219 }
6220
6221 @Override
6222 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6223 Bundle bOptions) {
6224 Preconditions.checkNotNull(intents, "intents");
6225 final String[] resolvedTypes = new String[intents.length];
6226
6227 // UID of the package on user userId.
6228 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6229 // packageUid may not be initialized.
6230 int packageUid = 0;
6231 final long ident = Binder.clearCallingIdentity();
6232
6233 try {
6234 for (int i = 0; i < intents.length; i++) {
6235 resolvedTypes[i] =
6236 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6237 }
6238
6239 packageUid = AppGlobals.getPackageManager().getPackageUid(
6240 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6241 } catch (RemoteException e) {
6242 // Shouldn't happen.
6243 } finally {
6244 Binder.restoreCallingIdentity(ident);
6245 }
6246
Riddle Hsu591bf612019-02-14 17:55:31 +08006247 return getActivityStartController().startActivitiesInPackage(
6248 packageUid, packageName,
6249 intents, resolvedTypes, null /* resultTo */,
6250 SafeActivityOptions.fromBundle(bOptions), userId,
6251 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6252 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006253 }
6254
6255 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006256 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6257 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6258 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6259 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006260 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006261 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006262 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6263 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6264 userId, validateIncomingUser, originatingPendingIntent,
6265 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006266 }
6267 }
6268
6269 @Override
6270 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6271 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6272 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006273 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006274 PendingIntentRecord originatingPendingIntent,
6275 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006276 synchronized (mGlobalLock) {
6277 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6278 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6279 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006280 validateIncomingUser, originatingPendingIntent,
6281 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006282 }
6283 }
6284
6285 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6287 Intent intent, Bundle options, int userId) {
6288 return ActivityTaskManagerService.this.startActivityAsUser(
6289 caller, callerPacakge, intent,
6290 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6291 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6292 false /*validateIncomingUser*/);
6293 }
6294
6295 @Override
lumark588a3e82018-07-20 18:53:54 +08006296 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006297 synchronized (mGlobalLock) {
6298
6299 // We might change the visibilities here, so prepare an empty app transition which
6300 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006301 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006302 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006303 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006304 return;
6305 }
Louis Chang677921f2019-12-06 16:44:24 +08006306 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006307 final boolean wasTransitionSet =
6308 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006310 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006311 }
Louis Chang149d5c82019-12-30 09:47:39 +08006312 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006313
6314 // If there was a transition set already we don't want to interfere with it as we
6315 // might be starting it too early.
6316 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006317 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006318 }
6319 }
6320 if (callback != null) {
6321 callback.run();
6322 }
6323 }
6324
6325 @Override
6326 public void notifyKeyguardTrustedChanged() {
6327 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006328 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006329 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006330 }
6331 }
6332 }
6333
6334 /**
6335 * Called after virtual display Id is updated by
6336 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6337 * {@param vrVr2dDisplayId}.
6338 */
6339 @Override
6340 public void setVr2dDisplayId(int vr2dDisplayId) {
6341 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6342 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006343 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006344 }
6345 }
6346
6347 @Override
6348 public void setFocusedActivity(IBinder token) {
6349 synchronized (mGlobalLock) {
6350 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6351 if (r == null) {
6352 throw new IllegalArgumentException(
6353 "setFocusedActivity: No activity record matching token=" + token);
6354 }
Louis Chang19443452018-10-09 12:10:21 +08006355 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006356 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006357 }
6358 }
6359 }
6360
6361 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006362 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006363 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006364 }
6365
6366 @Override
6367 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006368 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006369 }
6370
6371 @Override
6372 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006373 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006374 }
6375
6376 @Override
6377 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6378 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6379 }
6380
6381 @Override
6382 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006383 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006384 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006385
6386 @Override
6387 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6388 synchronized (mGlobalLock) {
6389 mActiveVoiceInteractionServiceComponent = component;
6390 }
6391 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006392
6393 @Override
6394 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6395 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6396 return;
6397 }
6398 synchronized (mGlobalLock) {
6399 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6400 if (types == null) {
6401 if (uid < 0) {
6402 return;
6403 }
6404 types = new ArrayMap<>();
6405 mAllowAppSwitchUids.put(userId, types);
6406 }
6407 if (uid < 0) {
6408 types.remove(type);
6409 } else {
6410 types.put(type, uid);
6411 }
6412 }
6413 }
6414
6415 @Override
6416 public void onUserStopped(int userId) {
6417 synchronized (mGlobalLock) {
6418 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6419 mAllowAppSwitchUids.remove(userId);
6420 }
6421 }
6422
6423 @Override
6424 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6425 synchronized (mGlobalLock) {
6426 return ActivityTaskManagerService.this.isGetTasksAllowed(
6427 caller, callingPid, callingUid);
6428 }
6429 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006430
Riddle Hsua0536432019-02-16 00:38:59 +08006431 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006432 @Override
6433 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006434 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006435 mProcessNames.put(proc.mName, proc.mUid, proc);
6436 }
6437 }
6438
Riddle Hsua0536432019-02-16 00:38:59 +08006439 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006440 @Override
6441 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006442 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006443 mProcessNames.remove(name, uid);
6444 }
6445 }
6446
Riddle Hsua0536432019-02-16 00:38:59 +08006447 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006448 @Override
6449 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006450 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006451 if (proc == mHomeProcess) {
6452 mHomeProcess = null;
6453 }
6454 if (proc == mPreviousProcess) {
6455 mPreviousProcess = null;
6456 }
6457 }
6458 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006459
Riddle Hsua0536432019-02-16 00:38:59 +08006460 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006461 @Override
6462 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006463 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006464 return mTopProcessState;
6465 }
6466 }
6467
Riddle Hsua0536432019-02-16 00:38:59 +08006468 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006469 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006470 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006471 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006472 return proc == mHeavyWeightProcess;
6473 }
6474 }
6475
Riddle Hsua0536432019-02-16 00:38:59 +08006476 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006477 @Override
6478 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006479 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006480 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6481 }
6482 }
6483
6484 @Override
6485 public void finishHeavyWeightApp() {
6486 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006487 if (mHeavyWeightProcess != null) {
6488 mHeavyWeightProcess.finishActivities();
6489 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006490 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6491 mHeavyWeightProcess);
6492 }
6493 }
6494
Riddle Hsua0536432019-02-16 00:38:59 +08006495 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006496 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006497 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006498 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006499 return isSleepingLocked();
6500 }
6501 }
6502
6503 @Override
6504 public boolean isShuttingDown() {
6505 synchronized (mGlobalLock) {
6506 return mShuttingDown;
6507 }
6508 }
6509
6510 @Override
6511 public boolean shuttingDown(boolean booted, int timeout) {
6512 synchronized (mGlobalLock) {
6513 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006514 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006515 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006516 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006517 return mStackSupervisor.shutdownLocked(timeout);
6518 }
6519 }
6520
6521 @Override
6522 public void enableScreenAfterBoot(boolean booted) {
6523 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006524 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006525 mWindowManager.enableScreenAfterBoot();
6526 updateEventDispatchingLocked(booted);
6527 }
6528 }
6529
6530 @Override
6531 public boolean showStrictModeViolationDialog() {
6532 synchronized (mGlobalLock) {
6533 return mShowDialogs && !mSleeping && !mShuttingDown;
6534 }
6535 }
6536
6537 @Override
6538 public void showSystemReadyErrorDialogsIfNeeded() {
6539 synchronized (mGlobalLock) {
6540 try {
6541 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6542 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6543 + " data partition or your device will be unstable.");
6544 mUiHandler.post(() -> {
6545 if (mShowDialogs) {
6546 AlertDialog d = new BaseErrorDialog(mUiContext);
6547 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6548 d.setCancelable(false);
6549 d.setTitle(mUiContext.getText(R.string.android_system_label));
6550 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6551 d.setButton(DialogInterface.BUTTON_POSITIVE,
6552 mUiContext.getText(R.string.ok),
6553 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6554 d.show();
6555 }
6556 });
6557 }
6558 } catch (RemoteException e) {
6559 }
6560
6561 if (!Build.isBuildConsistent()) {
6562 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6563 mUiHandler.post(() -> {
6564 if (mShowDialogs) {
6565 AlertDialog d = new BaseErrorDialog(mUiContext);
6566 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6567 d.setCancelable(false);
6568 d.setTitle(mUiContext.getText(R.string.android_system_label));
6569 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6570 d.setButton(DialogInterface.BUTTON_POSITIVE,
6571 mUiContext.getText(R.string.ok),
6572 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6573 d.show();
6574 }
6575 });
6576 }
6577 }
6578 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006579
6580 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006581 public void onProcessMapped(int pid, WindowProcessController proc) {
6582 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006583 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006584 }
6585 }
6586
6587 @Override
6588 public void onProcessUnMapped(int pid) {
6589 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006590 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006591 }
6592 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006593
6594 @Override
6595 public void onPackageDataCleared(String name) {
6596 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006597 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006598 mAppWarnings.onPackageDataCleared(name);
6599 }
6600 }
6601
6602 @Override
6603 public void onPackageUninstalled(String name) {
6604 synchronized (mGlobalLock) {
6605 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006606 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006607 }
6608 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006609
6610 @Override
6611 public void onPackageAdded(String name, boolean replacing) {
6612 synchronized (mGlobalLock) {
6613 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6614 }
6615 }
6616
6617 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006618 public void onPackageReplaced(ApplicationInfo aInfo) {
6619 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006620 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006621 }
6622 }
6623
6624 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006625 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6626 synchronized (mGlobalLock) {
6627 return compatibilityInfoForPackageLocked(ai);
6628 }
6629 }
6630
Yunfan Chen75157d72018-07-27 14:47:21 +09006631 /**
6632 * Set the corresponding display information for the process global configuration. To be
6633 * called when we need to show IME on a different display.
6634 *
6635 * @param pid The process id associated with the IME window.
6636 * @param displayId The ID of the display showing the IME.
6637 */
6638 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006639 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006640 // Don't update process-level configuration for Multi-Client IME process since other
6641 // IMEs on other displays will also receive this configuration change due to IME
6642 // services use the same application config/context.
6643 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006644
Yunfan Chen75157d72018-07-27 14:47:21 +09006645 if (pid == MY_PID || pid < 0) {
6646 if (DEBUG_CONFIGURATION) {
6647 Slog.w(TAG,
6648 "Trying to update display configuration for system/invalid process.");
6649 }
6650 return;
6651 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006652 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006653 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006654 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006655 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006656 // Call might come when display is not yet added or has been removed.
6657 if (DEBUG_CONFIGURATION) {
6658 Slog.w(TAG, "Trying to update display configuration for non-existing "
6659 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006660 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006661 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006662 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006663 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006664 if (process == null) {
6665 if (DEBUG_CONFIGURATION) {
6666 Slog.w(TAG, "Trying to update display configuration for invalid "
6667 + "process, pid=" + pid);
6668 }
6669 return;
6670 }
lumarkddc77fb2019-06-27 22:22:23 +08006671 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006672 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006673 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006674 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006675
6676 @Override
6677 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006678 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006679 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006680 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6681 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006682 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006683 }
6684 }
6685 }
6686
6687 @Override
6688 public void clearPendingResultForActivity(IBinder activityToken,
6689 WeakReference<PendingIntentRecord> pir) {
6690 synchronized (mGlobalLock) {
6691 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6692 if (r != null && r.pendingResults != null) {
6693 r.pendingResults.remove(pir);
6694 }
6695 }
6696 }
6697
6698 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006699 public ActivityTokens getTopActivityForTask(int taskId) {
6700 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006701 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006702 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006703 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6704 + " Requested task not found");
6705 return null;
6706 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006707 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006708 if (activity == null) {
6709 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6710 + " Requested activity not found");
6711 return null;
6712 }
6713 if (!activity.attachedToProcess()) {
6714 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6715 + activity);
6716 return null;
6717 }
6718 return new ActivityTokens(activity.appToken, activity.assistToken,
6719 activity.app.getThread());
6720 }
6721 }
6722
6723 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006724 public IIntentSender getIntentSender(int type, String packageName,
6725 int callingUid, int userId, IBinder token, String resultWho,
6726 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6727 Bundle bOptions) {
6728 synchronized (mGlobalLock) {
6729 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6730 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6731 }
6732 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006733
6734 @Override
6735 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6736 synchronized (mGlobalLock) {
6737 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6738 if (r == null) {
6739 return null;
6740 }
6741 if (r.mServiceConnectionsHolder == null) {
6742 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6743 ActivityTaskManagerService.this, r);
6744 }
6745
6746 return r.mServiceConnectionsHolder;
6747 }
6748 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006749
6750 @Override
6751 public Intent getHomeIntent() {
6752 synchronized (mGlobalLock) {
6753 return ActivityTaskManagerService.this.getHomeIntent();
6754 }
6755 }
6756
6757 @Override
6758 public boolean startHomeActivity(int userId, String reason) {
6759 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006760 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006761 }
6762 }
6763
6764 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006765 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006766 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006767 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006768 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006769 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006770 }
Chilun8b1f1be2019-03-13 17:14:36 +08006771 }
6772
6773 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006774 public boolean startHomeOnAllDisplays(int userId, String reason) {
6775 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006776 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006777 }
6778 }
6779
Riddle Hsua0536432019-02-16 00:38:59 +08006780 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006781 @Override
6782 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006783 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006784 if (mFactoryTest == FACTORY_TEST_OFF) {
6785 return false;
6786 }
6787 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6788 && wpc.mName.equals(mTopComponent.getPackageName())) {
6789 return true;
6790 }
6791 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6792 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6793 }
6794 }
6795
6796 @Override
6797 public void updateTopComponentForFactoryTest() {
6798 synchronized (mGlobalLock) {
6799 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6800 return;
6801 }
6802 final ResolveInfo ri = mContext.getPackageManager()
6803 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6804 final CharSequence errorMsg;
6805 if (ri != null) {
6806 final ActivityInfo ai = ri.activityInfo;
6807 final ApplicationInfo app = ai.applicationInfo;
6808 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6809 mTopAction = Intent.ACTION_FACTORY_TEST;
6810 mTopData = null;
6811 mTopComponent = new ComponentName(app.packageName, ai.name);
6812 errorMsg = null;
6813 } else {
6814 errorMsg = mContext.getResources().getText(
6815 com.android.internal.R.string.factorytest_not_system);
6816 }
6817 } else {
6818 errorMsg = mContext.getResources().getText(
6819 com.android.internal.R.string.factorytest_no_action);
6820 }
6821 if (errorMsg == null) {
6822 return;
6823 }
6824
6825 mTopAction = null;
6826 mTopData = null;
6827 mTopComponent = null;
6828 mUiHandler.post(() -> {
6829 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6830 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006831 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006832 });
6833 }
6834 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006835
Riddle Hsua0536432019-02-16 00:38:59 +08006836 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 @Override
6838 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6839 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006840 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006841 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006842 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843
6844 wpc.clearRecentTasks();
6845 wpc.clearActivities();
6846
6847 if (wpc.isInstrumenting()) {
6848 finishInstrumentationCallback.run();
6849 }
6850
Jorim Jaggid0752812018-10-16 16:07:20 +02006851 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006852 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006853 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006854 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006855 // If there was nothing to resume, and we are not already restarting
6856 // this process, but there is a visible activity that is hosted by the
6857 // process...then make sure all visible activities are running, taking
6858 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006859 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006860 !PRESERVE_WINDOWS);
6861 }
6862 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006863 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 }
6866 }
6867 }
6868
6869 @Override
6870 public void closeSystemDialogs(String reason) {
6871 enforceNotIsolatedCaller("closeSystemDialogs");
6872
6873 final int pid = Binder.getCallingPid();
6874 final int uid = Binder.getCallingUid();
6875 final long origId = Binder.clearCallingIdentity();
6876 try {
6877 synchronized (mGlobalLock) {
6878 // Only allow this from foreground processes, so that background
6879 // applications can't abuse it to prevent system UI from being shown.
6880 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006881 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006882 if (!proc.isPerceptible()) {
6883 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6884 + " from background process " + proc);
6885 return;
6886 }
6887 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 mWindowManager.closeSystemDialogs(reason);
6889
Louis Chang149d5c82019-12-30 09:47:39 +08006890 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006891 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006892 // Call into AM outside the synchronized block.
6893 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006894 } finally {
6895 Binder.restoreCallingIdentity(origId);
6896 }
6897 }
6898
6899 @Override
6900 public void cleanupDisabledPackageComponents(
6901 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6902 synchronized (mGlobalLock) {
6903 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006904 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006906 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 mStackSupervisor.scheduleIdleLocked();
6908 }
6909
6910 // Clean-up disabled tasks
6911 getRecentTasks().cleanupDisabledPackageTasksLocked(
6912 packageName, disabledClasses, userId);
6913 }
6914 }
6915
6916 @Override
6917 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6918 int userId) {
6919 synchronized (mGlobalLock) {
6920
6921 boolean didSomething =
6922 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006923 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006924 null, doit, evenPersistent, userId);
6925 return didSomething;
6926 }
6927 }
6928
6929 @Override
6930 public void resumeTopActivities(boolean scheduleIdle) {
6931 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006932 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006933 if (scheduleIdle) {
6934 mStackSupervisor.scheduleIdleLocked();
6935 }
6936 }
6937 }
6938
Riddle Hsua0536432019-02-16 00:38:59 +08006939 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 @Override
6941 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006942 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006943 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6944 }
6945 }
6946
Riddle Hsua0536432019-02-16 00:38:59 +08006947 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006948 @Override
6949 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006950 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006951 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6952 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6953 }
6954 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006955 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006956 } finally {
6957 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6958 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006959 }
6960 }
6961
6962 @Override
6963 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6964 try {
6965 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6966 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6967 }
6968 } catch (RemoteException ex) {
6969 throw new SecurityException("Fail to check is caller a privileged app", ex);
6970 }
6971
6972 synchronized (mGlobalLock) {
6973 final long ident = Binder.clearCallingIdentity();
6974 try {
6975 if (mAmInternal.shouldConfirmCredentials(userId)) {
6976 if (mKeyguardController.isKeyguardLocked()) {
6977 // Showing launcher to avoid user entering credential twice.
6978 startHomeActivity(currentUserId, "notifyLockedProfile");
6979 }
Louis Chang149d5c82019-12-30 09:47:39 +08006980 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006981 }
6982 } finally {
6983 Binder.restoreCallingIdentity(ident);
6984 }
6985 }
6986 }
6987
6988 @Override
6989 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6990 mAmInternal.enforceCallingPermission(
6991 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6992
6993 synchronized (mGlobalLock) {
6994 final long ident = Binder.clearCallingIdentity();
6995 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006996 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6997 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006998 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006999 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7000 UserHandle.CURRENT);
7001 } finally {
7002 Binder.restoreCallingIdentity(ident);
7003 }
7004 }
7005 }
7006
7007 @Override
7008 public void writeActivitiesToProto(ProtoOutputStream proto) {
7009 synchronized (mGlobalLock) {
7010 // The output proto of "activity --proto activities"
7011 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007012 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007013 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7014 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007015 }
7016 }
7017
7018 @Override
7019 public void saveANRState(String reason) {
7020 synchronized (mGlobalLock) {
7021 final StringWriter sw = new StringWriter();
7022 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7023 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7024 if (reason != null) {
7025 pw.println(" Reason: " + reason);
7026 }
7027 pw.println();
7028 getActivityStartController().dump(pw, " ", null);
7029 pw.println();
7030 pw.println("-------------------------------------------------------------------------------");
7031 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7032 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7033 "" /* header */);
7034 pw.println();
7035 pw.close();
7036
7037 mLastANRState = sw.toString();
7038 }
7039 }
7040
7041 @Override
7042 public void clearSavedANRState() {
7043 synchronized (mGlobalLock) {
7044 mLastANRState = null;
7045 }
7046 }
7047
7048 @Override
7049 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7050 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7051 synchronized (mGlobalLock) {
7052 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7053 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7054 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7055 dumpLastANRLocked(pw);
7056 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7057 dumpLastANRTracesLocked(pw);
7058 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7059 dumpActivityStarterLocked(pw, dumpPackage);
7060 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7061 dumpActivityContainersLocked(pw);
7062 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7063 if (getRecentTasks() != null) {
7064 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7065 }
7066 }
7067 }
7068 }
7069
7070 @Override
7071 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7072 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7073 int wakefulness) {
7074 synchronized (mGlobalLock) {
7075 if (mHomeProcess != null && (dumpPackage == null
7076 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7077 if (needSep) {
7078 pw.println();
7079 needSep = false;
7080 }
7081 pw.println(" mHomeProcess: " + mHomeProcess);
7082 }
7083 if (mPreviousProcess != null && (dumpPackage == null
7084 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7085 if (needSep) {
7086 pw.println();
7087 needSep = false;
7088 }
7089 pw.println(" mPreviousProcess: " + mPreviousProcess);
7090 }
7091 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7092 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7093 StringBuilder sb = new StringBuilder(128);
7094 sb.append(" mPreviousProcessVisibleTime: ");
7095 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7096 pw.println(sb);
7097 }
7098 if (mHeavyWeightProcess != null && (dumpPackage == null
7099 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7100 if (needSep) {
7101 pw.println();
7102 needSep = false;
7103 }
7104 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7105 }
7106 if (dumpPackage == null) {
7107 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007108 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 }
7110 if (dumpAll) {
7111 if (dumpPackage == null) {
7112 pw.println(" mConfigWillChange: "
7113 + getTopDisplayFocusedStack().mConfigWillChange);
7114 }
7115 if (mCompatModePackages.getPackages().size() > 0) {
7116 boolean printed = false;
7117 for (Map.Entry<String, Integer> entry
7118 : mCompatModePackages.getPackages().entrySet()) {
7119 String pkg = entry.getKey();
7120 int mode = entry.getValue();
7121 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7122 continue;
7123 }
7124 if (!printed) {
7125 pw.println(" mScreenCompatPackages:");
7126 printed = true;
7127 }
7128 pw.println(" " + pkg + ": " + mode);
7129 }
7130 }
7131 }
7132
7133 if (dumpPackage == null) {
7134 pw.println(" mWakefulness="
7135 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007136 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 if (mRunningVoice != null) {
7138 pw.println(" mRunningVoice=" + mRunningVoice);
7139 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7140 }
7141 pw.println(" mSleeping=" + mSleeping);
7142 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7143 pw.println(" mVrController=" + mVrController);
7144 }
7145 if (mCurAppTimeTracker != null) {
7146 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7147 }
7148 if (mAllowAppSwitchUids.size() > 0) {
7149 boolean printed = false;
7150 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7151 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7152 for (int j = 0; j < types.size(); j++) {
7153 if (dumpPackage == null ||
7154 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7155 if (needSep) {
7156 pw.println();
7157 needSep = false;
7158 }
7159 if (!printed) {
7160 pw.println(" mAllowAppSwitchUids:");
7161 printed = true;
7162 }
7163 pw.print(" User ");
7164 pw.print(mAllowAppSwitchUids.keyAt(i));
7165 pw.print(": Type ");
7166 pw.print(types.keyAt(j));
7167 pw.print(" = ");
7168 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7169 pw.println();
7170 }
7171 }
7172 }
7173 }
7174 if (dumpPackage == null) {
7175 if (mController != null) {
7176 pw.println(" mController=" + mController
7177 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7178 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007179 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7180 pw.println(" mLaunchingActivityWakeLock="
7181 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007182 }
7183
7184 return needSep;
7185 }
7186 }
7187
7188 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007189 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7190 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 synchronized (mGlobalLock) {
7192 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007193 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007195 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7196 if (mRunningVoice != null) {
7197 final long vrToken = proto.start(
7198 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7199 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7200 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007201 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007202 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7203 proto.end(vrToken);
7204 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007205 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007206 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007207 if (mController != null) {
7208 final long token = proto.start(CONTROLLER);
7209 proto.write(CONTROLLER, mController.toString());
7210 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7211 proto.end(token);
7212 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007213 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7214 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007215 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007216 }
7217
7218 if (mHomeProcess != null && (dumpPackage == null
7219 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007220 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007221 }
7222
7223 if (mPreviousProcess != null && (dumpPackage == null
7224 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007225 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007226 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7227 }
7228
7229 if (mHeavyWeightProcess != null && (dumpPackage == null
7230 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007231 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007232 }
7233
7234 for (Map.Entry<String, Integer> entry
7235 : mCompatModePackages.getPackages().entrySet()) {
7236 String pkg = entry.getKey();
7237 int mode = entry.getValue();
7238 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7239 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7240 proto.write(PACKAGE, pkg);
7241 proto.write(MODE, mode);
7242 proto.end(compatToken);
7243 }
7244 }
7245
7246 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007247 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007248 }
7249
7250 }
7251 }
7252
7253 @Override
7254 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7255 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7256 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007257 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7258 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007259 }
7260
7261 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007262 public void dumpForOom(PrintWriter pw) {
7263 synchronized (mGlobalLock) {
7264 pw.println(" mHomeProcess: " + mHomeProcess);
7265 pw.println(" mPreviousProcess: " + mPreviousProcess);
7266 if (mHeavyWeightProcess != null) {
7267 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7268 }
7269 }
7270 }
7271
7272 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007273 public boolean canGcNow() {
7274 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007275 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007276 }
7277 }
7278
Riddle Hsua0536432019-02-16 00:38:59 +08007279 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007280 @Override
7281 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007282 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007283 if (mRootWindowContainer == null) {
7284 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007285 // oomadj after AMS created.
7286 return null;
7287 }
Louis Chang149d5c82019-12-30 09:47:39 +08007288 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007289 return top != null ? top.app : null;
7290 }
7291 }
7292
Riddle Hsua0536432019-02-16 00:38:59 +08007293 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007294 @Override
7295 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007296 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007297 if (mRootWindowContainer != null) {
7298 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007299 }
7300 }
7301 }
7302
7303 @Override
7304 public void scheduleDestroyAllActivities(String reason) {
7305 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007306 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007307 }
7308 }
7309
7310 @Override
7311 public void removeUser(int userId) {
7312 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007313 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007314 }
7315 }
7316
7317 @Override
7318 public boolean switchUser(int userId, UserState userState) {
7319 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007320 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007321 }
7322 }
7323
7324 @Override
7325 public void onHandleAppCrash(WindowProcessController wpc) {
7326 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007327 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007328 }
7329 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007330
7331 @Override
7332 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7333 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007334 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007335 }
7336 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007337
Riddle Hsua0536432019-02-16 00:38:59 +08007338 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007339 @Override
7340 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007341 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007342 }
7343
Riddle Hsua0536432019-02-16 00:38:59 +08007344 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007345 @Override
7346 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007347 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007348 }
7349
Riddle Hsua0536432019-02-16 00:38:59 +08007350 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007351 @Override
7352 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007353 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007354 }
7355
Riddle Hsua0536432019-02-16 00:38:59 +08007356 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007357 @Override
7358 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007359 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007360 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007361
7362 @Override
7363 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007364 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007365 mPendingTempWhitelist.put(uid, tag);
7366 }
7367 }
7368
7369 @Override
7370 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007371 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007372 mPendingTempWhitelist.remove(uid);
7373 }
7374 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007375
7376 @Override
7377 public boolean handleAppCrashInActivityController(String processName, int pid,
7378 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7379 Runnable killCrashingAppCallback) {
7380 synchronized (mGlobalLock) {
7381 if (mController == null) {
7382 return false;
7383 }
7384
7385 try {
7386 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7387 stackTrace)) {
7388 killCrashingAppCallback.run();
7389 return true;
7390 }
7391 } catch (RemoteException e) {
7392 mController = null;
7393 Watchdog.getInstance().setActivityController(null);
7394 }
7395 return false;
7396 }
7397 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007398
7399 @Override
7400 public void removeRecentTasksByPackageName(String packageName, int userId) {
7401 synchronized (mGlobalLock) {
7402 mRecentTasks.removeTasksByPackageName(packageName, userId);
7403 }
7404 }
7405
7406 @Override
7407 public void cleanupRecentTasksForUser(int userId) {
7408 synchronized (mGlobalLock) {
7409 mRecentTasks.cleanupLocked(userId);
7410 }
7411 }
7412
7413 @Override
7414 public void loadRecentTasksForUser(int userId) {
7415 synchronized (mGlobalLock) {
7416 mRecentTasks.loadUserRecentsLocked(userId);
7417 }
7418 }
7419
7420 @Override
7421 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7422 synchronized (mGlobalLock) {
7423 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7424 }
7425 }
7426
7427 @Override
7428 public void flushRecentTasks() {
7429 mRecentTasks.flush();
7430 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007431
7432 @Override
7433 public WindowProcessController getHomeProcess() {
7434 synchronized (mGlobalLock) {
7435 return mHomeProcess;
7436 }
7437 }
7438
7439 @Override
7440 public WindowProcessController getPreviousProcess() {
7441 synchronized (mGlobalLock) {
7442 return mPreviousProcess;
7443 }
7444 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007445
7446 @Override
7447 public void clearLockedTasks(String reason) {
7448 synchronized (mGlobalLock) {
7449 getLockTaskController().clearLockedTasks(reason);
7450 }
7451 }
7452
7453 @Override
7454 public void updateUserConfiguration() {
7455 synchronized (mGlobalLock) {
7456 final Configuration configuration = new Configuration(getGlobalConfiguration());
7457 final int currentUserId = mAmInternal.getCurrentUserId();
7458 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7459 configuration, currentUserId, Settings.System.canWrite(mContext));
7460 updateConfigurationLocked(configuration, null /* starting */,
7461 false /* initLocale */, false /* persistent */, currentUserId,
7462 false /* deferResume */);
7463 }
7464 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007465
7466 @Override
7467 public boolean canShowErrorDialogs() {
7468 synchronized (mGlobalLock) {
7469 return mShowDialogs && !mSleeping && !mShuttingDown
7470 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7471 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7472 mAmInternal.getCurrentUserId())
7473 && !(UserManager.isDeviceInDemoMode(mContext)
7474 && mAmInternal.getCurrentUser().isDemo());
7475 }
7476 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007477
7478 @Override
7479 public void setProfileApp(String profileApp) {
7480 synchronized (mGlobalLock) {
7481 mProfileApp = profileApp;
7482 }
7483 }
7484
7485 @Override
7486 public void setProfileProc(WindowProcessController wpc) {
7487 synchronized (mGlobalLock) {
7488 mProfileProc = wpc;
7489 }
7490 }
7491
7492 @Override
7493 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7494 synchronized (mGlobalLock) {
7495 mProfilerInfo = profilerInfo;
7496 }
7497 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007498
7499 @Override
7500 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7501 synchronized (mGlobalLock) {
7502 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7503 }
7504 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007505
7506 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007507 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7508 boolean reducedResolution) {
7509 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7510 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007511 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007512
7513 @Override
7514 public boolean isUidForeground(int uid) {
7515 synchronized (mGlobalLock) {
7516 return ActivityTaskManagerService.this.isUidForeground(uid);
7517 }
7518 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007519
7520 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007521 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007522 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007523 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007524 }
7525 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007526
7527 @Override
7528 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007529 // Translate package names into UIDs
7530 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007531 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007532 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7533 if (uid >= 0) {
7534 result.add(uid);
7535 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007536 }
7537 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007538 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007539 }
7540 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007541 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007542}