blob: 331386f84402597486882eaca3eecd78f9d35379 [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;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.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 Ogunwale04d9cb52018-04-30 13:55:07 -0700309 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
310 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;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800379 RootActivityContainer mRootActivityContainer;
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
829 mTempConfig.setToDefaults();
830 mTempConfig.setLocales(LocaleList.getDefault());
831 mConfigurationSeq = mTempConfig.seq = 1;
832 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800833 mRootActivityContainer = new RootActivityContainer(this);
834 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700836 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700837 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700838 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700840 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700841 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700842 mKeyguardController = mStackSupervisor.getKeyguardController();
843 }
844
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700845 public void onActivityManagerInternalAdded() {
846 synchronized (mGlobalLock) {
847 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
848 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
849 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700850 }
851
Yunfan Chen75157d72018-07-27 14:47:21 +0900852 int increaseConfigurationSeqLocked() {
853 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
854 return mConfigurationSeq;
855 }
856
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700857 protected ActivityStackSupervisor createStackSupervisor() {
858 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
859 supervisor.initialize();
860 return supervisor;
861 }
862
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800863 protected AppWarnings createAppWarnings(
864 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
865 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
866 }
867
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700868 public void setWindowManager(WindowManagerService wm) {
869 synchronized (mGlobalLock) {
870 mWindowManager = wm;
871 mLockTaskController.setWindowManager(wm);
872 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800873 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700874 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700875 }
876
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700877 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
878 synchronized (mGlobalLock) {
879 mUsageStatsInternal = usageStatsManager;
880 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700881 }
882
Wale Ogunwalef6733932018-06-27 05:14:34 -0700883 UserManagerService getUserManager() {
884 if (mUserManager == null) {
885 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
886 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
887 }
888 return mUserManager;
889 }
890
891 AppOpsService getAppOpsService() {
892 if (mAppOpsService == null) {
893 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
894 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
895 }
896 return mAppOpsService;
897 }
898
899 boolean hasUserRestriction(String restriction, int userId) {
900 return getUserManager().hasUserRestriction(restriction, userId);
901 }
902
Michal Karpinski15486842019-04-25 17:33:42 +0100903 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
904 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700905 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100906 if (mode == AppOpsManager.MODE_DEFAULT) {
907 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
908 == PERMISSION_GRANTED;
909 }
910 return mode == AppOpsManager.MODE_ALLOWED;
911 }
912
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700913 @VisibleForTesting
914 protected void setRecentTasks(RecentTasks recentTasks) {
915 mRecentTasks = recentTasks;
916 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700917 }
918
919 RecentTasks getRecentTasks() {
920 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700921 }
922
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700923 ClientLifecycleManager getLifecycleManager() {
924 return mLifecycleManager;
925 }
926
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700927 ActivityStartController getActivityStartController() {
928 return mActivityStartController;
929 }
930
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700931 TaskChangeNotificationController getTaskChangeNotificationController() {
932 return mTaskChangeNotificationController;
933 }
934
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700935 LockTaskController getLockTaskController() {
936 return mLockTaskController;
937 }
938
Yunfan Chen75157d72018-07-27 14:47:21 +0900939 /**
940 * Return the global configuration used by the process corresponding to the input pid. This is
941 * usually the global configuration with some overrides specific to that process.
942 */
943 Configuration getGlobalConfigurationForCallingPid() {
944 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800945 return getGlobalConfigurationForPid(pid);
946 }
947
948 /**
949 * Return the global configuration used by the process corresponding to the given pid.
950 */
951 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900952 if (pid == MY_PID || pid < 0) {
953 return getGlobalConfiguration();
954 }
955 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100956 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 return app != null ? app.getConfiguration() : getGlobalConfiguration();
958 }
959 }
960
961 /**
962 * Return the device configuration info used by the process corresponding to the input pid.
963 * The value is consistent with the global configuration for the process.
964 */
965 @Override
966 public ConfigurationInfo getDeviceConfigurationInfo() {
967 ConfigurationInfo config = new ConfigurationInfo();
968 synchronized (mGlobalLock) {
969 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
970 config.reqTouchScreen = globalConfig.touchscreen;
971 config.reqKeyboardType = globalConfig.keyboard;
972 config.reqNavigation = globalConfig.navigation;
973 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
974 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
975 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
976 }
977 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
978 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
979 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
980 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700981 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900982 }
983 return config;
984 }
985
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700986 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700987 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700988 }
989
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700990 public static final class Lifecycle extends SystemService {
991 private final ActivityTaskManagerService mService;
992
993 public Lifecycle(Context context) {
994 super(context);
995 mService = new ActivityTaskManagerService(context);
996 }
997
998 @Override
999 public void onStart() {
1000 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001001 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 }
1003
Garfield Tan891146c2018-10-09 12:14:00 -07001004 @Override
1005 public void onUnlockUser(int userId) {
1006 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001007 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001008 }
1009 }
1010
1011 @Override
1012 public void onCleanupUser(int userId) {
1013 synchronized (mService.getGlobalLock()) {
1014 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1015 }
1016 }
1017
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001018 public ActivityTaskManagerService getService() {
1019 return mService;
1020 }
1021 }
1022
1023 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001024 public final int startActivity(IApplicationThread caller, String callingPackage,
1025 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1026 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1027 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1028 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1029 UserHandle.getCallingUserId());
1030 }
1031
1032 @Override
1033 public final int startActivities(IApplicationThread caller, String callingPackage,
1034 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1035 int userId) {
1036 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 enforceNotIsolatedCaller(reason);
1038 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001040 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1041 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1042 reason, null /* originatingPendingIntent */,
1043 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 }
1045
1046 @Override
1047 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1048 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1049 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1050 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1051 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1052 true /*validateIncomingUser*/);
1053 }
1054
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001055 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1057 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1058 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001059 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001061 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1063
1064 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001065 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 .setCaller(caller)
1067 .setCallingPackage(callingPackage)
1068 .setResolvedType(resolvedType)
1069 .setResultTo(resultTo)
1070 .setResultWho(resultWho)
1071 .setRequestCode(requestCode)
1072 .setStartFlags(startFlags)
1073 .setProfilerInfo(profilerInfo)
1074 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001075 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 .execute();
1077
1078 }
1079
1080 @Override
1081 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1082 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1084 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 // Refuse possible leaked file descriptors
1086 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1087 throw new IllegalArgumentException("File descriptors passed in Intent");
1088 }
1089
1090 if (!(target instanceof PendingIntentRecord)) {
1091 throw new IllegalArgumentException("Bad PendingIntent object");
1092 }
1093
1094 PendingIntentRecord pir = (PendingIntentRecord)target;
1095
1096 synchronized (mGlobalLock) {
1097 // If this is coming from the currently resumed activity, it is
1098 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001099 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001100 if (stack.mResumedActivity != null &&
1101 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001102 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 }
1104 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001105 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001107 }
1108
1109 @Override
1110 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1111 Bundle bOptions) {
1112 // Refuse possible leaked file descriptors
1113 if (intent != null && intent.hasFileDescriptors()) {
1114 throw new IllegalArgumentException("File descriptors passed in Intent");
1115 }
1116 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1117
1118 synchronized (mGlobalLock) {
1119 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1120 if (r == null) {
1121 SafeActivityOptions.abort(options);
1122 return false;
1123 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 // The caller is not running... d'oh!
1126 SafeActivityOptions.abort(options);
1127 return false;
1128 }
1129 intent = new Intent(intent);
1130 // The caller is not allowed to change the data.
1131 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1132 // And we are resetting to find the next component...
1133 intent.setComponent(null);
1134
1135 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1136
1137 ActivityInfo aInfo = null;
1138 try {
1139 List<ResolveInfo> resolves =
1140 AppGlobals.getPackageManager().queryIntentActivities(
1141 intent, r.resolvedType,
1142 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1143 UserHandle.getCallingUserId()).getList();
1144
1145 // Look for the original activity in the list...
1146 final int N = resolves != null ? resolves.size() : 0;
1147 for (int i=0; i<N; i++) {
1148 ResolveInfo rInfo = resolves.get(i);
1149 if (rInfo.activityInfo.packageName.equals(r.packageName)
1150 && rInfo.activityInfo.name.equals(r.info.name)) {
1151 // We found the current one... the next matching is
1152 // after it.
1153 i++;
1154 if (i<N) {
1155 aInfo = resolves.get(i).activityInfo;
1156 }
1157 if (debug) {
1158 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1159 + "/" + r.info.name);
1160 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1161 ? "null" : aInfo.packageName + "/" + aInfo.name));
1162 }
1163 break;
1164 }
1165 }
1166 } catch (RemoteException e) {
1167 }
1168
1169 if (aInfo == null) {
1170 // Nobody who is next!
1171 SafeActivityOptions.abort(options);
1172 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1173 return false;
1174 }
1175
1176 intent.setComponent(new ComponentName(
1177 aInfo.applicationInfo.packageName, aInfo.name));
1178 intent.setFlags(intent.getFlags()&~(
1179 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1180 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1181 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1182 FLAG_ACTIVITY_NEW_TASK));
1183
1184 // Okay now we need to start the new activity, replacing the currently running activity.
1185 // This is a little tricky because we want to start the new one as if the current one is
1186 // finished, but not finish the current one first so that there is no flicker.
1187 // And thus...
1188 final boolean wasFinishing = r.finishing;
1189 r.finishing = true;
1190
1191 // Propagate reply information over to the new activity.
1192 final ActivityRecord resultTo = r.resultTo;
1193 final String resultWho = r.resultWho;
1194 final int requestCode = r.requestCode;
1195 r.resultTo = null;
1196 if (resultTo != null) {
1197 resultTo.removeResultsLocked(r, resultWho, requestCode);
1198 }
1199
1200 final long origId = Binder.clearCallingIdentity();
1201 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001202 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001203 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001204 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001205 .setResolvedType(r.resolvedType)
1206 .setActivityInfo(aInfo)
1207 .setResultTo(resultTo != null ? resultTo.appToken : null)
1208 .setResultWho(resultWho)
1209 .setRequestCode(requestCode)
1210 .setCallingPid(-1)
1211 .setCallingUid(r.launchedFromUid)
1212 .setCallingPackage(r.launchedFromPackage)
1213 .setRealCallingPid(-1)
1214 .setRealCallingUid(r.launchedFromUid)
1215 .setActivityOptions(options)
1216 .execute();
1217 Binder.restoreCallingIdentity(origId);
1218
1219 r.finishing = wasFinishing;
1220 if (res != ActivityManager.START_SUCCESS) {
1221 return false;
1222 }
1223 return true;
1224 }
1225 }
1226
1227 @Override
1228 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1229 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1230 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1231 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001232 enforceNotIsolatedCaller("startActivityAndWait");
1233 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1234 userId, "startActivityAndWait");
1235 // TODO: Switch to user app stacks here.
1236 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1237 .setCaller(caller)
1238 .setCallingPackage(callingPackage)
1239 .setResolvedType(resolvedType)
1240 .setResultTo(resultTo)
1241 .setResultWho(resultWho)
1242 .setRequestCode(requestCode)
1243 .setStartFlags(startFlags)
1244 .setActivityOptions(bOptions)
1245 .setUserId(userId)
1246 .setProfilerInfo(profilerInfo)
1247 .setWaitResult(res)
1248 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001249 return res;
1250 }
1251
1252 @Override
1253 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1254 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1255 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001256 enforceNotIsolatedCaller("startActivityWithConfig");
1257 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1258 "startActivityWithConfig");
1259 // TODO: Switch to user app stacks here.
1260 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1261 .setCaller(caller)
1262 .setCallingPackage(callingPackage)
1263 .setResolvedType(resolvedType)
1264 .setResultTo(resultTo)
1265 .setResultWho(resultWho)
1266 .setRequestCode(requestCode)
1267 .setStartFlags(startFlags)
1268 .setGlobalConfiguration(config)
1269 .setActivityOptions(bOptions)
1270 .setUserId(userId)
1271 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001272 }
1273
Alison Cichowlas3e340502018-08-07 17:15:01 -04001274
1275 @Override
1276 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1277 int callingUid = Binder.getCallingUid();
1278 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1279 throw new SecurityException("Only the system process can request a permission token, "
1280 + "received request from uid: " + callingUid);
1281 }
1282 IBinder permissionToken = new Binder();
1283 synchronized (mGlobalLock) {
1284 mStartActivitySources.put(permissionToken, delegatorToken);
1285 }
1286
1287 Message expireMsg = PooledLambda.obtainMessage(
1288 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1289 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1290
1291 Message forgetMsg = PooledLambda.obtainMessage(
1292 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1293 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1294
1295 return permissionToken;
1296 }
1297
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 @Override
1299 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1300 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001301 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1302 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001303 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001304 // permission grants) as any app that may launch one of your own activities. So we only
1305 // allow this in two cases:
1306 // 1) The caller is an activity that is part of the core framework, and then only when it
1307 // is running as the system.
1308 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1309 // can only be requested by a system activity, which may then delegate this call to
1310 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 final ActivityRecord sourceRecord;
1312 final int targetUid;
1313 final String targetPackage;
1314 final boolean isResolver;
1315 synchronized (mGlobalLock) {
1316 if (resultTo == null) {
1317 throw new SecurityException("Must be called from an activity");
1318 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319 final IBinder sourceToken;
1320 if (permissionToken != null) {
1321 // To even attempt to use a permissionToken, an app must also have this signature
1322 // permission.
1323 mAmInternal.enforceCallingPermission(
1324 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1325 "startActivityAsCaller");
1326 // If called with a permissionToken, we want the sourceRecord from the delegator
1327 // activity that requested this token.
1328 sourceToken = mStartActivitySources.remove(permissionToken);
1329 if (sourceToken == null) {
1330 // Invalid permissionToken, check if it recently expired.
1331 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1332 throw new SecurityException("Called with expired permission token: "
1333 + permissionToken);
1334 } else {
1335 throw new SecurityException("Called with invalid permission token: "
1336 + permissionToken);
1337 }
1338 }
1339 } else {
1340 // This method was called directly by the source.
1341 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001343
Wale Ogunwaled32da472018-11-16 07:19:28 -08001344 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001345 if (sourceRecord == null) {
1346 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 }
1348 if (sourceRecord.app == null) {
1349 throw new SecurityException("Called without a process attached to activity");
1350 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001351
1352 // Whether called directly or from a delegate, the source activity must be from the
1353 // android package.
1354 if (!sourceRecord.info.packageName.equals("android")) {
1355 throw new SecurityException("Must be called from an activity that is "
1356 + "declared in the android package");
1357 }
1358
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001359 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 // This is still okay, as long as this activity is running under the
1361 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001362 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001363 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001364 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 + " must be system uid or original calling uid "
1366 + sourceRecord.launchedFromUid);
1367 }
1368 }
1369 if (ignoreTargetSecurity) {
1370 if (intent.getComponent() == null) {
1371 throw new SecurityException(
1372 "Component must be specified with ignoreTargetSecurity");
1373 }
1374 if (intent.getSelector() != null) {
1375 throw new SecurityException(
1376 "Selector not allowed with ignoreTargetSecurity");
1377 }
1378 }
1379 targetUid = sourceRecord.launchedFromUid;
1380 targetPackage = sourceRecord.launchedFromPackage;
1381 isResolver = sourceRecord.isResolverOrChildActivity();
1382 }
1383
1384 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001385 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386 }
1387
1388 // TODO: Switch to user app stacks here.
1389 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001390 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 .setCallingUid(targetUid)
1392 .setCallingPackage(targetPackage)
1393 .setResolvedType(resolvedType)
1394 .setResultTo(resultTo)
1395 .setResultWho(resultWho)
1396 .setRequestCode(requestCode)
1397 .setStartFlags(startFlags)
1398 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001399 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1401 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001402 // The target may well be in the background, which would normally prevent it
1403 // from starting an activity. Here we definitely want the start to succeed.
1404 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 .execute();
1406 } catch (SecurityException e) {
1407 // XXX need to figure out how to propagate to original app.
1408 // A SecurityException here is generally actually a fault of the original
1409 // calling activity (such as a fairly granting permissions), so propagate it
1410 // back to them.
1411 /*
1412 StringBuilder msg = new StringBuilder();
1413 msg.append("While launching");
1414 msg.append(intent.toString());
1415 msg.append(": ");
1416 msg.append(e.getMessage());
1417 */
1418 throw e;
1419 }
1420 }
1421
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001422 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1423 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1424 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1425 }
1426
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 @Override
1428 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1429 Intent intent, String resolvedType, IVoiceInteractionSession session,
1430 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1431 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001432 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001433 if (session == null || interactor == null) {
1434 throw new NullPointerException("null session or interactor");
1435 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001438 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 .setCallingUid(callingUid)
1440 .setCallingPackage(callingPackage)
1441 .setResolvedType(resolvedType)
1442 .setVoiceSession(session)
1443 .setVoiceInteractor(interactor)
1444 .setStartFlags(startFlags)
1445 .setProfilerInfo(profilerInfo)
1446 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001447 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001448 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 .execute();
1450 }
1451
1452 @Override
1453 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1454 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1456 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001458 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 .setCallingUid(callingUid)
1460 .setCallingPackage(callingPackage)
1461 .setResolvedType(resolvedType)
1462 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001463 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001464 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 .execute();
1466 }
1467
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 /**
1469 * Start the recents activity to perform the recents animation.
1470 *
1471 * @param intent The intent to start the recents activity.
1472 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1473 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001475 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1476 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001477 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001479 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 final long origId = Binder.clearCallingIdentity();
1481 try {
1482 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001483 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1484 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001485 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001486
1487 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001488 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001489 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001490 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001491 if (recentsAnimationRunner == null) {
1492 anim.preloadRecentsActivity();
1493 } else {
1494 anim.startRecentsActivity(recentsAnimationRunner);
1495 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 }
1497 } finally {
1498 Binder.restoreCallingIdentity(origId);
1499 }
1500 }
1501
1502 @Override
1503 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001504 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001505 "startActivityFromRecents()");
1506
1507 final int callingPid = Binder.getCallingPid();
1508 final int callingUid = Binder.getCallingUid();
1509 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1510 final long origId = Binder.clearCallingIdentity();
1511 try {
1512 synchronized (mGlobalLock) {
1513 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1514 safeOptions);
1515 }
1516 } finally {
1517 Binder.restoreCallingIdentity(origId);
1518 }
1519 }
1520
1521 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001522 * Public API to check if the client is allowed to start an activity on specified display.
1523 *
1524 * If the target display is private or virtual, some restrictions will apply.
1525 *
1526 * @param displayId Target display id.
1527 * @param intent Intent used to launch the activity.
1528 * @param resolvedType The MIME type of the intent.
1529 * @param userId The id of the user for whom the call is made.
1530 * @return {@code true} if a call to start an activity on the target display should succeed and
1531 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1532 */
1533 @Override
1534 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1535 String resolvedType, int userId) {
1536 final int callingUid = Binder.getCallingUid();
1537 final int callingPid = Binder.getCallingPid();
1538 final long origId = Binder.clearCallingIdentity();
1539
1540 try {
1541 // Collect information about the target of the Intent.
1542 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1543 0 /* startFlags */, null /* profilerInfo */, userId,
1544 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1545 UserHandle.USER_NULL));
1546 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1547
1548 synchronized (mGlobalLock) {
1549 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1550 aInfo);
1551 }
1552 } finally {
1553 Binder.restoreCallingIdentity(origId);
1554 }
1555 }
1556
1557 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001558 * This is the internal entry point for handling Activity.finish().
1559 *
1560 * @param token The Binder token referencing the Activity we want to finish.
1561 * @param resultCode Result code, if any, from this Activity.
1562 * @param resultData Result data (Intent), if any, from this Activity.
1563 * @param finishTask Whether to finish the task associated with this Activity.
1564 *
1565 * @return Returns true if the activity successfully finished, or false if it is still running.
1566 */
1567 @Override
1568 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1569 int finishTask) {
1570 // Refuse possible leaked file descriptors
1571 if (resultData != null && resultData.hasFileDescriptors()) {
1572 throw new IllegalArgumentException("File descriptors passed in Intent");
1573 }
1574
1575 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (r == null) {
1578 return true;
1579 }
1580 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001581 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001582 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 if (rootR == null) {
1584 Slog.w(TAG, "Finishing task with all activities already finished");
1585 }
1586 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1587 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001588 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001589 return false;
1590 }
1591
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001592 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1593 // We should consolidate.
1594 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001596 final ActivityRecord next =
1597 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 if (next != null) {
1599 // ask watcher if this is allowed
1600 boolean resumeOK = true;
1601 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001602 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001604 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 Watchdog.getInstance().setActivityController(null);
1606 }
1607
1608 if (!resumeOK) {
1609 Slog.i(TAG, "Not finishing activity because controller resumed");
1610 return false;
1611 }
1612 }
1613 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001614
1615 // note down that the process has finished an activity and is in background activity
1616 // starts grace period
1617 if (r.app != null) {
1618 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1619 }
1620
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001622 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 try {
1624 boolean res;
1625 final boolean finishWithRootActivity =
1626 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1627 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1628 || (finishWithRootActivity && r == rootR)) {
1629 // If requested, remove the task that is associated to this activity only if it
1630 // was the root activity in the task. The result code and data is ignored
1631 // because we don't support returning them across task boundaries. Also, to
1632 // keep backwards compatibility we remove the task from recents when finishing
1633 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001634 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001636 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001637 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001638 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001640 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001641 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642 if (!res) {
1643 Slog.i(TAG, "Failed to finish by app-request");
1644 }
1645 }
1646 return res;
1647 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001648 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public boolean finishActivityAffinity(IBinder token) {
1656 synchronized (mGlobalLock) {
1657 final long origId = Binder.clearCallingIdentity();
1658 try {
1659 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1660 if (r == null) {
1661 return false;
1662 }
1663
1664 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1665 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001666 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 return false;
1668 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001669
1670 final PooledFunction p = PooledLambda.obtainFunction(
1671 ActivityRecord::finishIfSameAffinity, r,
1672 PooledLambda.__(ActivityRecord.class));
1673 r.getTask().forAllActivities(
1674 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1675 p.recycle();
1676
Andrii Kuliande93eff2019-07-12 12:21:27 -07001677 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 } finally {
1679 Binder.restoreCallingIdentity(origId);
1680 }
1681 }
1682 }
1683
1684 @Override
1685 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1686 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001687 try {
1688 WindowProcessController proc = null;
1689 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001690 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001691 ActivityStack stack = ActivityRecord.getStackLocked(token);
1692 if (stack == null) {
1693 return;
1694 }
1695 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1696 false /* fromTimeout */, false /* processPausingActivities */, config);
1697 if (r != null) {
1698 proc = r.app;
1699 }
1700 if (stopProfiling && proc != null) {
1701 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 }
1703 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001704 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001705 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001706 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001708 }
1709
1710 @Override
1711 public final void activityResumed(IBinder token) {
1712 final long origId = Binder.clearCallingIdentity();
1713 synchronized (mGlobalLock) {
1714 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001715 }
1716 Binder.restoreCallingIdentity(origId);
1717 }
1718
1719 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001720 public final void activityTopResumedStateLost() {
1721 final long origId = Binder.clearCallingIdentity();
1722 synchronized (mGlobalLock) {
1723 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1724 }
1725 Binder.restoreCallingIdentity(origId);
1726 }
1727
1728 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 public final void activityPaused(IBinder token) {
1730 final long origId = Binder.clearCallingIdentity();
1731 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001732 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 ActivityStack stack = ActivityRecord.getStackLocked(token);
1734 if (stack != null) {
1735 stack.activityPausedLocked(token, false);
1736 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001737 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001738 }
1739 Binder.restoreCallingIdentity(origId);
1740 }
1741
1742 @Override
1743 public final void activityStopped(IBinder token, Bundle icicle,
1744 PersistableBundle persistentState, CharSequence description) {
1745 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1746
1747 // Refuse possible leaked file descriptors
1748 if (icicle != null && icicle.hasFileDescriptors()) {
1749 throw new IllegalArgumentException("File descriptors passed in Bundle");
1750 }
1751
1752 final long origId = Binder.clearCallingIdentity();
1753
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001754 String restartingName = null;
1755 int restartingUid = 0;
1756 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001758 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001759 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001761 if (r.attachedToProcess()
1762 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1763 // The activity was requested to restart from
1764 // {@link #restartActivityProcessIfVisible}.
1765 restartingName = r.app.mName;
1766 restartingUid = r.app.mUid;
1767 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001768 r.activityStoppedLocked(icicle, persistentState, description);
1769 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001770 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 }
1772
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001773 if (restartingName != null) {
1774 // In order to let the foreground activity can be restarted with its saved state from
1775 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1776 // until the activity reports stopped with the state. And the activity record will be
1777 // kept because the record state is restarting, then the activity will be restarted
1778 // immediately if it is still the top one.
1779 mStackSupervisor.removeRestartTimeouts(r);
1780 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1781 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001782 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783
1784 Binder.restoreCallingIdentity(origId);
1785 }
1786
1787 @Override
1788 public final void activityDestroyed(IBinder token) {
1789 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1790 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001791 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001792 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001793 try {
1794 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1795 if (activity != null) {
1796 activity.destroyed("activityDestroyed");
1797 }
1798 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001799 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001800 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 }
1802 }
1803 }
1804
1805 @Override
1806 public final void activityRelaunched(IBinder token) {
1807 final long origId = Binder.clearCallingIdentity();
1808 synchronized (mGlobalLock) {
1809 mStackSupervisor.activityRelaunchedLocked(token);
1810 }
1811 Binder.restoreCallingIdentity(origId);
1812 }
1813
1814 public final void activitySlept(IBinder token) {
1815 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1816
1817 final long origId = Binder.clearCallingIdentity();
1818
1819 synchronized (mGlobalLock) {
1820 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 if (r != null) {
1822 mStackSupervisor.activitySleptLocked(r);
1823 }
1824 }
1825
1826 Binder.restoreCallingIdentity(origId);
1827 }
1828
1829 @Override
1830 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1831 synchronized (mGlobalLock) {
1832 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1833 if (r == null) {
1834 return;
1835 }
1836 final long origId = Binder.clearCallingIdentity();
1837 try {
1838 r.setRequestedOrientation(requestedOrientation);
1839 } finally {
1840 Binder.restoreCallingIdentity(origId);
1841 }
1842 }
1843 }
1844
1845 @Override
1846 public int getRequestedOrientation(IBinder token) {
1847 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001848 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1849 return (r != null)
1850 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 }
1852 }
1853
1854 @Override
1855 public void setImmersive(IBinder token, boolean immersive) {
1856 synchronized (mGlobalLock) {
1857 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1858 if (r == null) {
1859 throw new IllegalArgumentException();
1860 }
1861 r.immersive = immersive;
1862
1863 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001864 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001866 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 }
1868 }
1869 }
1870
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 void applyUpdateLockStateLocked(ActivityRecord r) {
1872 // Modifications to the UpdateLock state are done on our handler, outside
1873 // the activity manager's locks. The new state is determined based on the
1874 // state *now* of the relevant activity record. The object is passed to
1875 // the handler solely for logging detail, not to be consulted/modified.
1876 final boolean nextState = r != null && r.immersive;
1877 mH.post(() -> {
1878 if (mUpdateLock.isHeld() != nextState) {
1879 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1880 "Applying new update lock state '" + nextState + "' for " + r);
1881 if (nextState) {
1882 mUpdateLock.acquire();
1883 } else {
1884 mUpdateLock.release();
1885 }
1886 }
1887 });
1888 }
1889
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 @Override
1891 public boolean isImmersive(IBinder token) {
1892 synchronized (mGlobalLock) {
1893 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1894 if (r == null) {
1895 throw new IllegalArgumentException();
1896 }
1897 return r.immersive;
1898 }
1899 }
1900
1901 @Override
1902 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001905 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 return (r != null) ? r.immersive : false;
1907 }
1908 }
1909
1910 @Override
1911 public void overridePendingTransition(IBinder token, String packageName,
1912 int enterAnim, int exitAnim) {
1913 synchronized (mGlobalLock) {
1914 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1915 if (self == null) {
1916 return;
1917 }
1918
1919 final long origId = Binder.clearCallingIdentity();
1920
1921 if (self.isState(
1922 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001923 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001924 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001925 }
1926
1927 Binder.restoreCallingIdentity(origId);
1928 }
1929 }
1930
1931 @Override
1932 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001933 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001935 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 if (r == null) {
1937 return ActivityManager.COMPAT_MODE_UNKNOWN;
1938 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001939 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 }
1941 }
1942
1943 @Override
1944 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001945 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001949 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001950 if (r == null) {
1951 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1952 return;
1953 }
1954 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001955 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001956 }
1957 }
1958
1959 @Override
1960 public int getLaunchedFromUid(IBinder activityToken) {
1961 ActivityRecord srec;
1962 synchronized (mGlobalLock) {
1963 srec = ActivityRecord.forTokenLocked(activityToken);
1964 }
1965 if (srec == null) {
1966 return -1;
1967 }
1968 return srec.launchedFromUid;
1969 }
1970
1971 @Override
1972 public String getLaunchedFromPackage(IBinder activityToken) {
1973 ActivityRecord srec;
1974 synchronized (mGlobalLock) {
1975 srec = ActivityRecord.forTokenLocked(activityToken);
1976 }
1977 if (srec == null) {
1978 return null;
1979 }
1980 return srec.launchedFromPackage;
1981 }
1982
1983 @Override
1984 public boolean convertFromTranslucent(IBinder token) {
1985 final long origId = Binder.clearCallingIdentity();
1986 try {
1987 synchronized (mGlobalLock) {
1988 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1989 if (r == null) {
1990 return false;
1991 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001992 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001993 }
1994 } finally {
1995 Binder.restoreCallingIdentity(origId);
1996 }
1997 }
1998
1999 @Override
2000 public boolean convertToTranslucent(IBinder token, Bundle options) {
2001 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2002 final long origId = Binder.clearCallingIdentity();
2003 try {
2004 synchronized (mGlobalLock) {
2005 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2006 if (r == null) {
2007 return false;
2008 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002009 final ActivityRecord under = r.getTask().getActivityBelow(r);
2010 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002011 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2012 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002013 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 }
2015 } finally {
2016 Binder.restoreCallingIdentity(origId);
2017 }
2018 }
2019
2020 @Override
2021 public void notifyActivityDrawn(IBinder token) {
2022 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2023 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002024 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002026 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 }
2028 }
2029 }
2030
2031 @Override
2032 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2033 synchronized (mGlobalLock) {
2034 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2035 if (r == null) {
2036 return;
2037 }
2038 r.reportFullyDrawnLocked(restoredFromBundle);
2039 }
2040 }
2041
2042 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002043 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002044 synchronized (mGlobalLock) {
2045 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2046 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2047 return stack.mDisplayId;
2048 }
2049 return DEFAULT_DISPLAY;
2050 }
2051 }
2052
2053 @Override
2054 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002055 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 long ident = Binder.clearCallingIdentity();
2057 try {
2058 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002059 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002061 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 }
2063 return null;
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(ident);
2067 }
2068 }
2069
2070 @Override
2071 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2074 final long callingId = Binder.clearCallingIdentity();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 if (stack == null) {
2079 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2080 return;
2081 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002082 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002083 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002084 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 }
2087 } finally {
2088 Binder.restoreCallingIdentity(callingId);
2089 }
2090 }
2091
2092 @Override
2093 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002094 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002095 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2096 final long callingId = Binder.clearCallingIdentity();
2097 try {
2098 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002099 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002100 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 if (task == null) {
2102 return;
2103 }
2104 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002105 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002106 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 }
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(callingId);
2111 }
2112 }
2113
2114 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002115 public void restartActivityProcessIfVisible(IBinder activityToken) {
2116 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2117 final long callingId = Binder.clearCallingIdentity();
2118 try {
2119 synchronized (mGlobalLock) {
2120 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2121 if (r == null) {
2122 return;
2123 }
2124 r.restartProcessIfVisible();
2125 }
2126 } finally {
2127 Binder.restoreCallingIdentity(callingId);
2128 }
2129 }
2130
2131 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002133 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134 synchronized (mGlobalLock) {
2135 final long ident = Binder.clearCallingIdentity();
2136 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002137 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 "remove-task");
2139 } finally {
2140 Binder.restoreCallingIdentity(ident);
2141 }
2142 }
2143 }
2144
2145 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002146 public void removeAllVisibleRecentTasks() {
2147 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2148 synchronized (mGlobalLock) {
2149 final long ident = Binder.clearCallingIdentity();
2150 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002151 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002152 } finally {
2153 Binder.restoreCallingIdentity(ident);
2154 }
2155 }
2156 }
2157
2158 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2160 synchronized (mGlobalLock) {
2161 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2162 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002163 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 }
2165 }
2166 return false;
2167 }
2168
2169 @Override
2170 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2171 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002172
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002173 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002174 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2175 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002176 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002177 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002178 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002179 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002180 }
2181 }
2182
2183 /**
2184 * Attempts to move a task backwards in z-order (the order of activities within the task is
2185 * unchanged).
2186 *
2187 * There are several possible results of this call:
2188 * - if the task is locked, then we will show the lock toast
2189 * - if there is a task behind the provided task, then that task is made visible and resumed as
2190 * this task is moved to the back
2191 * - otherwise, if there are no other tasks in the stack:
2192 * - if this task is in the pinned stack, then we remove the stack completely, which will
2193 * have the effect of moving the task to the top or bottom of the fullscreen stack
2194 * (depending on whether it is visible)
2195 * - otherwise, we simply return home and hide this task
2196 *
2197 * @param token A reference to the activity we wish to move
2198 * @param nonRoot If false then this only works if the activity is the root
2199 * of a task; if true it will work for any activity in a task.
2200 * @return Returns true if the move completed, false if not.
2201 */
2202 @Override
2203 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002204 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002205 synchronized (mGlobalLock) {
2206 final long origId = Binder.clearCallingIdentity();
2207 try {
2208 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Changcdec0802019-11-11 11:45:07 +08002209 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002211 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002212 }
2213 } finally {
2214 Binder.restoreCallingIdentity(origId);
2215 }
2216 }
2217 return false;
2218 }
2219
2220 @Override
2221 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 long ident = Binder.clearCallingIdentity();
2224 Rect rect = new Rect();
2225 try {
2226 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002227 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2229 if (task == null) {
2230 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2231 return rect;
2232 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002233 if (task.getParent() != null) {
2234 rect.set(task.getBounds());
2235 } else if (task.mLastNonFullscreenBounds != null) {
2236 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 }
2238 }
2239 } finally {
2240 Binder.restoreCallingIdentity(ident);
2241 }
2242 return rect;
2243 }
2244
2245 @Override
2246 public ActivityManager.TaskDescription getTaskDescription(int id) {
2247 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002248 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Changcdec0802019-11-11 11:45:07 +08002250 final Task tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002251 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2252 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002253 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002254 }
2255 }
2256 return null;
2257 }
2258
2259 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002260 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2261 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2262 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2263 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2264 return;
2265 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002266 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 synchronized (mGlobalLock) {
2268 final long ident = Binder.clearCallingIdentity();
2269 try {
Louis Changcdec0802019-11-11 11:45:07 +08002270 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002271 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002272 if (task == null) {
2273 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2274 return;
2275 }
2276
2277 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2278 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2279
2280 if (!task.isActivityTypeStandardOrUndefined()) {
2281 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2282 + " non-standard task " + taskId + " to windowing mode="
2283 + windowingMode);
2284 }
2285
2286 final ActivityStack stack = task.getStack();
2287 if (toTop) {
2288 stack.moveToFront("setTaskWindowingMode", task);
2289 }
2290 stack.setWindowingMode(windowingMode);
2291 } finally {
2292 Binder.restoreCallingIdentity(ident);
2293 }
2294 }
2295 }
2296
2297 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002299 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 ActivityRecord r = getCallingRecordLocked(token);
2301 return r != null ? r.info.packageName : null;
2302 }
2303 }
2304
2305 @Override
2306 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 ActivityRecord r = getCallingRecordLocked(token);
2309 return r != null ? r.intent.getComponent() : null;
2310 }
2311 }
2312
2313 private ActivityRecord getCallingRecordLocked(IBinder token) {
2314 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2315 if (r == null) {
2316 return null;
2317 }
2318 return r.resultTo;
2319 }
2320
2321 @Override
2322 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002323 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002324
2325 synchronized (mGlobalLock) {
2326 final long origId = Binder.clearCallingIdentity();
2327 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002328 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002329 } finally {
2330 Binder.restoreCallingIdentity(origId);
2331 }
2332 }
2333 }
2334
Mark Renouf446251d2019-04-26 10:22:41 -04002335 @Override
2336 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2337 synchronized (mGlobalLock) {
2338 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2339 if (r == null) {
2340 return;
2341 }
2342 ActivityStack stack = r.getActivityStack();
2343 if (stack != null && stack.isSingleTaskInstance()) {
2344 // Single-task stacks are used for activities which are presented in floating
2345 // windows above full screen activities. Instead of directly finishing the
2346 // task, a task change listener is used to notify SystemUI so the action can be
2347 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002348 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002349 mTaskChangeNotificationController
2350 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2351 } else {
2352 try {
2353 callback.requestFinish();
2354 } catch (RemoteException e) {
2355 Slog.e(TAG, "Failed to invoke request finish callback", e);
2356 }
2357 }
2358 }
2359 }
2360
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002361 /**
2362 * TODO: Add mController hook
2363 */
2364 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2366 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368
2369 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2370 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2372 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 }
2374 }
2375
Ricky Waiaca8a772019-04-04 16:01:06 +01002376 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2377 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002379
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 final int callingPid = Binder.getCallingPid();
2381 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002382 if (!isSameApp(callingUid, callingPackage)) {
2383 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2384 + Binder.getCallingPid() + " as package " + callingPackage;
2385 Slog.w(TAG, msg);
2386 throw new SecurityException(msg);
2387 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 SafeActivityOptions.abort(options);
2390 return;
2391 }
2392 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002393 WindowProcessController callerApp = null;
2394 if (appThread != null) {
2395 callerApp = getProcessController(appThread);
2396 }
2397 final ActivityStarter starter = getActivityStartController().obtainStarter(
2398 null /* intent */, "moveTaskToFront");
2399 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2400 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002401 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002402 return;
2403 }
2404 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 try {
Louis Changcdec0802019-11-11 11:45:07 +08002406 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 if (task == null) {
2408 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002409 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 return;
2411 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002412 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002413 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002414 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002415 return;
2416 }
2417 ActivityOptions realOptions = options != null
2418 ? options.getOptions(mStackSupervisor)
2419 : null;
2420 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2421 false /* forceNonResizable */);
2422
Wale Ogunwale21e06482019-11-18 05:14:15 -08002423 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 if (topActivity != null) {
2425
2426 // We are reshowing a task, use a starting window to hide the initial draw delay
2427 // so the transition can start earlier.
2428 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2429 true /* taskSwitch */, fromRecents);
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(origId);
2433 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002434 }
2435
Ricky Waiaca8a772019-04-04 16:01:06 +01002436 /**
2437 * Return true if callingUid is system, or packageName belongs to that callingUid.
2438 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002439 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002440 try {
2441 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2442 if (packageName == null) {
2443 return false;
2444 }
2445 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2446 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2447 UserHandle.getUserId(callingUid));
2448 return UserHandle.isSameApp(callingUid, uid);
2449 }
2450 } catch (RemoteException e) {
2451 // Should not happen
2452 }
2453 return true;
2454 }
2455
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002456 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2457 int callingPid, int callingUid, String name) {
2458 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2459 return true;
2460 }
2461
2462 if (getRecentTasks().isCallerRecents(sourceUid)) {
2463 return true;
2464 }
2465
2466 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2467 if (perm == PackageManager.PERMISSION_GRANTED) {
2468 return true;
2469 }
2470 if (checkAllowAppSwitchUid(sourceUid)) {
2471 return true;
2472 }
2473
2474 // If the actual IPC caller is different from the logical source, then
2475 // also see if they are allowed to control app switches.
2476 if (callingUid != -1 && callingUid != sourceUid) {
2477 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2478 if (perm == PackageManager.PERMISSION_GRANTED) {
2479 return true;
2480 }
2481 if (checkAllowAppSwitchUid(callingUid)) {
2482 return true;
2483 }
2484 }
2485
2486 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2487 return false;
2488 }
2489
2490 private boolean checkAllowAppSwitchUid(int uid) {
2491 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2492 if (types != null) {
2493 for (int i = types.size() - 1; i >= 0; i--) {
2494 if (types.valueAt(i).intValue() == uid) {
2495 return true;
2496 }
2497 }
2498 }
2499 return false;
2500 }
2501
2502 @Override
2503 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2504 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2505 "setActivityController()");
2506 synchronized (mGlobalLock) {
2507 mController = controller;
2508 mControllerIsAMonkey = imAMonkey;
2509 Watchdog.getInstance().setActivityController(controller);
2510 }
2511 }
2512
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002513 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 synchronized (mGlobalLock) {
2515 return mController != null && mControllerIsAMonkey;
2516 }
2517 }
2518
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002519 @Override
2520 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2521 synchronized (mGlobalLock) {
2522 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2523 }
2524 }
2525
2526 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002527 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2528 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2529 }
2530
2531 @Override
2532 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2533 @WindowConfiguration.ActivityType int ignoreActivityType,
2534 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2535 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002536 final int callingPid = Binder.getCallingPid();
2537 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002538 final int[] profileIds = getUserManager().getProfileIds(
2539 UserHandle.getUserId(callingUid), true);
2540 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2541 for (int i = 0; i < profileIds.length; i++) {
2542 callingProfileIds.add(profileIds[i]);
2543 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002544 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2545
2546 synchronized (mGlobalLock) {
2547 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2548
Nicholas Sauer0259e532019-08-30 08:24:55 -07002549 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002550 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002551 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 }
2553
2554 return list;
2555 }
2556
2557 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2559 synchronized (mGlobalLock) {
2560 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002561 try {
2562 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2563 if (r == null) return;
2564
2565 final PooledConsumer c = PooledLambda.obtainConsumer(
2566 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2567 r, resultWho, requestCode);
2568 // TODO: This should probably only loop over the task since you need to be in the
2569 // same task to return results.
2570 r.getActivityStack().forAllActivities(c);
2571 c.recycle();
2572
2573 updateOomAdj();
2574 } finally {
2575 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 }
2578 }
2579
2580 @Override
2581 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 ActivityStack stack = ActivityRecord.getStackLocked(token);
2584 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002585 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002586 }
2587 return false;
2588 }
2589 }
2590
2591 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002593 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 synchronized (mGlobalLock) {
2595 final long ident = Binder.clearCallingIdentity();
2596 try {
Louis Changcdec0802019-11-11 11:45:07 +08002597 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 if (task == null) {
2599 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2600 return;
2601 }
2602
2603 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2604 + " to stackId=" + stackId + " toTop=" + toTop);
2605
Wale Ogunwaled32da472018-11-16 07:19:28 -08002606 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 if (stack == null) {
2608 throw new IllegalStateException(
2609 "moveTaskToStack: No stack for stackId=" + stackId);
2610 }
2611 if (!stack.isActivityTypeStandardOrUndefined()) {
2612 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2613 + taskId + " to stack " + stackId);
2614 }
2615 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002616 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2618 }
2619 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2620 "moveTaskToStack");
2621 } finally {
2622 Binder.restoreCallingIdentity(ident);
2623 }
2624 }
2625 }
2626
2627 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002628 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2629 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002630
2631 final long ident = Binder.clearCallingIdentity();
2632 try {
2633 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002634 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2635 if (stack == null) {
2636 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2637 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002638 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002639 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2640 throw new IllegalArgumentException("Stack: " + stackId
2641 + " doesn't support animated resize.");
2642 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002643 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002644 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645 }
2646 } finally {
2647 Binder.restoreCallingIdentity(ident);
2648 }
2649 }
2650
wilsonshih5c4cf522019-01-25 09:03:47 +08002651 @Override
2652 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2653 int animationDuration) {
2654 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2655
2656 final long ident = Binder.clearCallingIdentity();
2657 try {
2658 synchronized (mGlobalLock) {
2659 if (xOffset == 0 && yOffset == 0) {
2660 return;
2661 }
2662 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2663 if (stack == null) {
2664 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2665 return;
2666 }
2667 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2668 throw new IllegalArgumentException("Stack: " + stackId
2669 + " doesn't support animated resize.");
2670 }
2671 final Rect destBounds = new Rect();
2672 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002673 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002674 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2675 return;
2676 }
2677 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002678 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002679 animationDuration, false /* fromFullscreen */);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 /**
2686 * Moves the specified task to the primary-split-screen stack.
2687 *
2688 * @param taskId Id of task to move.
2689 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2690 * exist already. See
2691 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2692 * and
2693 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2694 * @param toTop If the task and stack should be moved to the top.
2695 * @param animate Whether we should play an animation for the moving the task.
2696 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2697 * stack. Pass {@code null} to use default bounds.
2698 * @param showRecents If the recents activity should be shown on the other side of the task
2699 * going into split-screen mode.
2700 */
2701 @Override
2702 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2703 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002704 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002705 "setTaskWindowingModeSplitScreenPrimary()");
2706 synchronized (mGlobalLock) {
2707 final long ident = Binder.clearCallingIdentity();
2708 try {
Louis Changcdec0802019-11-11 11:45:07 +08002709 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002710 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002711 if (task == null) {
2712 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2713 return false;
2714 }
2715 if (DEBUG_STACK) Slog.d(TAG_STACK,
2716 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2717 + " to createMode=" + createMode + " toTop=" + toTop);
2718 if (!task.isActivityTypeStandardOrUndefined()) {
2719 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2720 + " non-standard task " + taskId + " to split-screen windowing mode");
2721 }
2722
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002723 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002724 final int windowingMode = task.getWindowingMode();
2725 final ActivityStack stack = task.getStack();
2726 if (toTop) {
2727 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2728 }
2729 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002730 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2731 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 return windowingMode != task.getWindowingMode();
2733 } finally {
2734 Binder.restoreCallingIdentity(ident);
2735 }
2736 }
2737 }
2738
2739 /**
2740 * Removes stacks in the input windowing modes from the system if they are of activity type
2741 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2742 */
2743 @Override
2744 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002745 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002746 "removeStacksInWindowingModes()");
2747
2748 synchronized (mGlobalLock) {
2749 final long ident = Binder.clearCallingIdentity();
2750 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002751 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002752 } finally {
2753 Binder.restoreCallingIdentity(ident);
2754 }
2755 }
2756 }
2757
2758 @Override
2759 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002761 "removeStacksWithActivityTypes()");
2762
2763 synchronized (mGlobalLock) {
2764 final long ident = Binder.clearCallingIdentity();
2765 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
2770 }
2771 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002772
2773 @Override
2774 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2775 int userId) {
2776 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002777 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2778 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002780 final boolean detailed = checkGetTasksPermission(
2781 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2782 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 == PackageManager.PERMISSION_GRANTED;
2784
2785 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002786 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 callingUid);
2788 }
2789 }
2790
2791 @Override
2792 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002793 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 long ident = Binder.clearCallingIdentity();
2795 try {
2796 synchronized (mGlobalLock) {
Evan Roskyfd439692019-11-06 16:12:59 -08002797 return mRootActivityContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 }
2799 } finally {
2800 Binder.restoreCallingIdentity(ident);
2801 }
2802 }
2803
2804 @Override
2805 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002806 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002807 long ident = Binder.clearCallingIdentity();
2808 try {
2809 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002810 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 }
2812 } finally {
2813 Binder.restoreCallingIdentity(ident);
2814 }
2815 }
2816
2817 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002818 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2819 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2820 long ident = Binder.clearCallingIdentity();
2821 try {
2822 synchronized (mGlobalLock) {
2823 return mRootActivityContainer.getAllStackInfos(displayId);
2824 }
2825 } finally {
2826 Binder.restoreCallingIdentity(ident);
2827 }
2828 }
2829
2830 @Override
2831 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2832 int displayId) {
2833 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2834 long ident = Binder.clearCallingIdentity();
2835 try {
2836 synchronized (mGlobalLock) {
2837 return mRootActivityContainer.getStackInfo(windowingMode, activityType, displayId);
2838 }
2839 } finally {
2840 Binder.restoreCallingIdentity(ident);
2841 }
2842 }
2843
2844 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002846 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002847 final long callingUid = Binder.getCallingUid();
2848 final long origId = Binder.clearCallingIdentity();
2849 try {
2850 synchronized (mGlobalLock) {
2851 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002852 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2854 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2855 }
2856 } finally {
2857 Binder.restoreCallingIdentity(origId);
2858 }
2859 }
2860
2861 @Override
2862 public void startLockTaskModeByToken(IBinder token) {
2863 synchronized (mGlobalLock) {
2864 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2865 if (r == null) {
2866 return;
2867 }
Louis Changcdec0802019-11-11 11:45:07 +08002868 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002869 }
2870 }
2871
2872 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002873 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002874 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 // This makes inner call to look as if it was initiated by system.
2876 long ident = Binder.clearCallingIdentity();
2877 try {
2878 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08002879 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002880 MATCH_TASK_IN_STACKS_ONLY);
2881 if (task == null) {
2882 return;
2883 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884
2885 // When starting lock task mode the stack must be in front and focused
2886 task.getStack().moveToFront("startSystemLockTaskMode");
2887 startLockTaskModeLocked(task, true /* isSystemCaller */);
2888 }
2889 } finally {
2890 Binder.restoreCallingIdentity(ident);
2891 }
2892 }
2893
2894 @Override
2895 public void stopLockTaskModeByToken(IBinder token) {
2896 synchronized (mGlobalLock) {
2897 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2898 if (r == null) {
2899 return;
2900 }
Louis Changcdec0802019-11-11 11:45:07 +08002901 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 }
2903 }
2904
2905 /**
2906 * This API should be called by SystemUI only when user perform certain action to dismiss
2907 * lock task mode. We should only dismiss pinned lock task mode in this case.
2908 */
2909 @Override
2910 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002911 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2913 }
2914
Louis Changcdec0802019-11-11 11:45:07 +08002915 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002916 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2917 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2918 return;
2919 }
2920
Wale Ogunwaled32da472018-11-16 07:19:28 -08002921 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002922 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 throw new IllegalArgumentException("Invalid task, not in foreground");
2924 }
2925
2926 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2927 // system or a specific app.
2928 // * System-initiated requests will only start the pinned mode (screen pinning)
2929 // * App-initiated requests
2930 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2931 // - will start the pinned mode, otherwise
2932 final int callingUid = Binder.getCallingUid();
2933 long ident = Binder.clearCallingIdentity();
2934 try {
2935 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002936 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002938 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 } finally {
2940 Binder.restoreCallingIdentity(ident);
2941 }
2942 }
2943
Louis Changcdec0802019-11-11 11:45:07 +08002944 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 final int callingUid = Binder.getCallingUid();
2946 long ident = Binder.clearCallingIdentity();
2947 try {
2948 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002949 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 }
2951 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2952 // task and jumping straight into a call in the case of emergency call back.
2953 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2954 if (tm != null) {
2955 tm.showInCallScreen(false);
2956 }
2957 } finally {
2958 Binder.restoreCallingIdentity(ident);
2959 }
2960 }
2961
2962 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002963 public void updateLockTaskPackages(int userId, String[] packages) {
2964 final int callingUid = Binder.getCallingUid();
2965 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2966 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2967 "updateLockTaskPackages()");
2968 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002969 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002970 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2971 + Arrays.toString(packages));
2972 getLockTaskController().updateLockTaskPackages(userId, packages);
2973 }
2974 }
2975
2976 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 public boolean isInLockTaskMode() {
2978 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2979 }
2980
2981 @Override
2982 public int getLockTaskModeState() {
2983 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002984 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 }
2986 }
2987
2988 @Override
2989 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2990 synchronized (mGlobalLock) {
2991 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2992 if (r != null) {
2993 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002994 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002995 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 }
2997 }
2998 }
2999
3000 @Override
3001 public Bundle getActivityOptions(IBinder token) {
3002 final long origId = Binder.clearCallingIdentity();
3003 try {
3004 synchronized (mGlobalLock) {
3005 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3006 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003007 final ActivityOptions activityOptions = r.takeOptionsLocked(
3008 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 return activityOptions == null ? null : activityOptions.toBundle();
3010 }
3011 return null;
3012 }
3013 } finally {
3014 Binder.restoreCallingIdentity(origId);
3015 }
3016 }
3017
3018 @Override
3019 public List<IBinder> getAppTasks(String callingPackage) {
3020 int callingUid = Binder.getCallingUid();
3021 long ident = Binder.clearCallingIdentity();
3022 try {
3023 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003024 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 }
3026 } finally {
3027 Binder.restoreCallingIdentity(ident);
3028 }
3029 }
3030
3031 @Override
3032 public void finishVoiceTask(IVoiceInteractionSession session) {
3033 synchronized (mGlobalLock) {
3034 final long origId = Binder.clearCallingIdentity();
3035 try {
3036 // TODO: VI Consider treating local voice interactions and voice tasks
3037 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003038 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 } finally {
3040 Binder.restoreCallingIdentity(origId);
3041 }
3042 }
3043
3044 }
3045
3046 @Override
3047 public boolean isTopOfTask(IBinder token) {
3048 synchronized (mGlobalLock) {
3049 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003050 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 }
3052 }
3053
3054 @Override
3055 public void notifyLaunchTaskBehindComplete(IBinder token) {
3056 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3057 }
3058
3059 @Override
3060 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003061 mH.post(() -> {
3062 synchronized (mGlobalLock) {
3063 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003064 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003065 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003066 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003067 } catch (RemoteException e) {
3068 }
3069 }
3070 }
3071
3072 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 }
3074
3075 /** Called from an app when assist data is ready. */
3076 @Override
3077 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3078 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003079 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 synchronized (pae) {
3081 pae.result = extras;
3082 pae.structure = structure;
3083 pae.content = content;
3084 if (referrer != null) {
3085 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3086 }
3087 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003088 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003089 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003090 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 structure.setHomeActivity(pae.isHome);
3092 }
3093 pae.haveResult = true;
3094 pae.notifyAll();
3095 if (pae.intent == null && pae.receiver == null) {
3096 // Caller is just waiting for the result.
3097 return;
3098 }
3099 }
3100 // We are now ready to launch the assist activity.
3101 IAssistDataReceiver sendReceiver = null;
3102 Bundle sendBundle = null;
3103 synchronized (mGlobalLock) {
3104 buildAssistBundleLocked(pae, extras);
3105 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003106 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 if (!exists) {
3108 // Timed out.
3109 return;
3110 }
3111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003112 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 // Caller wants result sent back to them.
3114 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003115 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003116 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003117 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3118 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3120 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3121 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3122 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3123 }
3124 }
3125 if (sendReceiver != null) {
3126 try {
3127 sendReceiver.onHandleAssistData(sendBundle);
3128 } catch (RemoteException e) {
3129 }
3130 return;
3131 }
3132
3133 final long ident = Binder.clearCallingIdentity();
3134 try {
3135 if (TextUtils.equals(pae.intent.getAction(),
3136 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003137 // Start voice interaction through VoiceInteractionManagerService.
3138 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3139 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 } else {
3141 pae.intent.replaceExtras(pae.extras);
3142 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3143 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3144 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003145 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003146
3147 try {
3148 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3149 } catch (ActivityNotFoundException e) {
3150 Slog.w(TAG, "No activity to handle assist action.", e);
3151 }
3152 }
3153 } finally {
3154 Binder.restoreCallingIdentity(ident);
3155 }
3156 }
3157
3158 @Override
3159 public int addAppTask(IBinder activityToken, Intent intent,
3160 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3161 final int callingUid = Binder.getCallingUid();
3162 final long callingIdent = Binder.clearCallingIdentity();
3163
3164 try {
3165 synchronized (mGlobalLock) {
3166 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3167 if (r == null) {
3168 throw new IllegalArgumentException("Activity does not exist; token="
3169 + activityToken);
3170 }
3171 ComponentName comp = intent.getComponent();
3172 if (comp == null) {
3173 throw new IllegalArgumentException("Intent " + intent
3174 + " must specify explicit component");
3175 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003176 if (thumbnail.getWidth() != mThumbnailWidth
3177 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 throw new IllegalArgumentException("Bad thumbnail size: got "
3179 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 }
3182 if (intent.getSelector() != null) {
3183 intent.setSelector(null);
3184 }
3185 if (intent.getSourceBounds() != null) {
3186 intent.setSourceBounds(null);
3187 }
3188 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3189 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3190 // The caller has added this as an auto-remove task... that makes no
3191 // sense, so turn off auto-remove.
3192 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3193 }
3194 }
3195 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3196 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3197 if (ainfo.applicationInfo.uid != callingUid) {
3198 throw new SecurityException(
3199 "Can't add task for another application: target uid="
3200 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3201 }
3202
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003203 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003204 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003205 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003207 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003209 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 return INVALID_TASK_ID;
3211 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003212 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003213
3214 // TODO: Send the thumbnail to WM to store it.
3215
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003216 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003217 }
3218 } finally {
3219 Binder.restoreCallingIdentity(callingIdent);
3220 }
3221 }
3222
3223 @Override
3224 public Point getAppTaskThumbnailSize() {
3225 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003226 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 }
3228 }
3229
3230 @Override
3231 public void setTaskResizeable(int taskId, int resizeableMode) {
3232 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003233 final Task task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3235 if (task == null) {
3236 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3237 return;
3238 }
3239 task.setResizeMode(resizeableMode);
3240 }
3241 }
3242
3243 @Override
3244 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 long ident = Binder.clearCallingIdentity();
3247 try {
3248 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08003249 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003250 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 if (task == null) {
3252 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3253 return;
3254 }
3255 // Place the task in the right stack if it isn't there already based on
3256 // the requested bounds.
3257 // The stack transition logic is:
3258 // - a null bounds on a freeform task moves that task to fullscreen
3259 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3260 // that task to freeform
3261 // - otherwise the task is not moved
3262 ActivityStack stack = task.getStack();
3263 if (!task.getWindowConfiguration().canResizeTask()) {
3264 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3265 }
3266 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3267 stack = stack.getDisplay().getOrCreateStack(
3268 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3269 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3270 stack = stack.getDisplay().getOrCreateStack(
3271 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3272 }
3273
3274 // Reparent the task to the right stack if necessary
3275 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3276 if (stack != task.getStack()) {
3277 // Defer resume until the task is resized below
3278 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3279 DEFER_RESUME, "resizeTask");
3280 preserveWindow = false;
3281 }
3282
3283 // After reparenting (which only resizes the task to the stack bounds), resize the
3284 // task to the actual bounds provided
3285 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3286 }
3287 } finally {
3288 Binder.restoreCallingIdentity(ident);
3289 }
3290 }
3291
Evan Roskyddedfd42019-10-04 13:38:38 -07003292 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3293 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003294 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003295 throw new RuntimeException("Invalid token in task transaction");
3296 }
3297 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3298 // masks here.
3299 int configMask = change.getConfigSetMask();
3300 int windowMask = change.getWindowSetMask();
3301 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3302 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3303 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3304 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3305 c.setTo(change.getConfiguration(), configMask, windowMask);
3306 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003307 // TODO(b/145675353): remove the following once we could apply new bounds to the
3308 // pinned stack together with its children.
3309 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3310 }
3311
3312 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3313 int windowMask, Configuration config) {
3314 if ((container instanceof ActivityStack)
3315 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3316 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3317 final ActivityStack stack = (ActivityStack) container;
3318 if (stack.inPinnedWindowingMode()) {
3319 stack.resize(config.windowConfiguration.getBounds(),
3320 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3321 PRESERVE_WINDOWS, true /* deferResume */);
3322 }
3323 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003324 }
3325
3326 @Override
3327 public void applyContainerTransaction(WindowContainerTransaction t) {
3328 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3329 long ident = Binder.clearCallingIdentity();
3330 try {
3331 if (t == null) {
3332 return;
3333 }
3334 synchronized (mGlobalLock) {
3335 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3336 t.getChanges().entrySet().iterator();
3337 while (entries.hasNext()) {
3338 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3339 entries.next();
3340 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3341 entry.getKey()).getContainer();
3342 sanitizeAndApplyConfigChange(cc, entry.getValue());
3343 }
3344 }
3345 } finally {
3346 Binder.restoreCallingIdentity(ident);
3347 }
3348 }
3349
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 @Override
3351 public boolean releaseActivityInstance(IBinder token) {
3352 synchronized (mGlobalLock) {
3353 final long origId = Binder.clearCallingIdentity();
3354 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003355 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3356 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357 return false;
3358 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003359 r.destroyImmediately(true /* removeFromApp */, "app-req");
3360 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003361 } finally {
3362 Binder.restoreCallingIdentity(origId);
3363 }
3364 }
3365 }
3366
3367 @Override
3368 public void releaseSomeActivities(IApplicationThread appInt) {
3369 synchronized (mGlobalLock) {
3370 final long origId = Binder.clearCallingIdentity();
3371 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003372 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003373 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 } finally {
3375 Binder.restoreCallingIdentity(origId);
3376 }
3377 }
3378 }
3379
3380 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003381 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003382 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 != PackageManager.PERMISSION_GRANTED) {
3384 throw new SecurityException("Requires permission "
3385 + android.Manifest.permission.DEVICE_POWER);
3386 }
3387
3388 synchronized (mGlobalLock) {
3389 long ident = Binder.clearCallingIdentity();
3390 if (mKeyguardShown != keyguardShowing) {
3391 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003392 final Message msg = PooledLambda.obtainMessage(
3393 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3394 keyguardShowing);
3395 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397 try {
wilsonshih177261f2019-02-22 12:02:18 +08003398 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 } finally {
3400 Binder.restoreCallingIdentity(ident);
3401 }
3402 }
3403
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003404 mH.post(() -> {
3405 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3406 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3407 }
3408 });
3409 }
3410
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003411 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 mH.post(() -> {
3413 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3414 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3415 }
3416 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 }
3418
3419 @Override
3420 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3422 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423
3424 final File passedIconFile = new File(filePath);
3425 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3426 passedIconFile.getName());
3427 if (!legitIconFile.getPath().equals(filePath)
3428 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3429 throw new IllegalArgumentException("Bad file path: " + filePath
3430 + " passed for userId " + userId);
3431 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003432 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 }
3434
3435 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003436 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003437 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003438 synchronized (mGlobalLock) {
3439 final long ident = Binder.clearCallingIdentity();
3440 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003441 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003442 if (stack == null) {
3443 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3444 return;
3445 }
3446 if (!stack.isActivityTypeStandardOrUndefined()) {
3447 throw new IllegalArgumentException(
3448 "Removing non-standard stack is not allowed.");
3449 }
3450 mStackSupervisor.removeStack(stack);
3451 } finally {
3452 Binder.restoreCallingIdentity(ident);
3453 }
3454 }
3455 }
3456
3457 @Override
3458 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460
3461 synchronized (mGlobalLock) {
3462 final long ident = Binder.clearCallingIdentity();
3463 try {
3464 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3465 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003466 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 } finally {
3468 Binder.restoreCallingIdentity(ident);
3469 }
3470 }
3471 }
3472
3473 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003474 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003475 synchronized (mGlobalLock) {
3476 long ident = Binder.clearCallingIdentity();
3477 try {
3478 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3479 if (r == null) {
3480 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003481 "toggleFreeformWindowingMode: No activity record matching token="
3482 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 }
3484
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003485 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003486 if (stack == null) {
3487 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3488 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489 }
3490
Yunfan Chend967af82019-01-17 18:30:18 +09003491 if (!stack.inFreeformWindowingMode()
3492 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3493 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3494 + "toggle between fullscreen and freeform.");
3495 }
3496
3497 if (stack.inFreeformWindowingMode()) {
3498 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003499 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003500 throw new IllegalStateException("Size-compat windows are currently not"
3501 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003502 } else if (stack.getParent().inFreeformWindowingMode()) {
3503 // If the window is on a freeform display, set it to undefined. It will be
3504 // resolved to freeform and it can adjust windowing mode when the display mode
3505 // changes in runtime.
3506 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003507 } else {
3508 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3509 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003510 } finally {
3511 Binder.restoreCallingIdentity(ident);
3512 }
3513 }
3514 }
3515
3516 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3517 @Override
3518 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003519 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003520 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003521 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 }
3523
3524 /** Unregister a task stack listener so that it stops receiving callbacks. */
3525 @Override
3526 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003527 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003528 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003529 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003530 }
3531
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003532 @Override
3533 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3534 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3535 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3536 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3537 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3538 }
3539
3540 @Override
3541 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3542 IBinder activityToken, int flags) {
3543 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3544 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3545 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3546 }
3547
3548 @Override
3549 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3550 Bundle args) {
3551 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3552 true /* focused */, true /* newSessionId */, userHandle, args,
3553 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3554 }
3555
3556 @Override
3557 public Bundle getAssistContextExtras(int requestType) {
3558 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3559 null, null, true /* focused */, true /* newSessionId */,
3560 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3561 if (pae == null) {
3562 return null;
3563 }
3564 synchronized (pae) {
3565 while (!pae.haveResult) {
3566 try {
3567 pae.wait();
3568 } catch (InterruptedException e) {
3569 }
3570 }
3571 }
3572 synchronized (mGlobalLock) {
3573 buildAssistBundleLocked(pae, pae.result);
3574 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003576 }
3577 return pae.extras;
3578 }
3579
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003580 /**
3581 * Binder IPC calls go through the public entry point.
3582 * This can be called with or without the global lock held.
3583 */
3584 private static int checkCallingPermission(String permission) {
3585 return checkPermission(
3586 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3587 }
3588
3589 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003590 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003591 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3592 mAmInternal.enforceCallingPermission(permission, func);
3593 }
3594 }
3595
3596 @VisibleForTesting
3597 int checkGetTasksPermission(String permission, int pid, int uid) {
3598 return checkPermission(permission, pid, uid);
3599 }
3600
3601 static int checkPermission(String permission, int pid, int uid) {
3602 if (permission == null) {
3603 return PackageManager.PERMISSION_DENIED;
3604 }
3605 return checkComponentPermission(permission, pid, uid, -1, true);
3606 }
3607
Wale Ogunwale214f3482018-10-04 11:00:47 -07003608 public static int checkComponentPermission(String permission, int pid, int uid,
3609 int owningUid, boolean exported) {
3610 return ActivityManagerService.checkComponentPermission(
3611 permission, pid, uid, owningUid, exported);
3612 }
3613
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003614 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3615 if (getRecentTasks().isCallerRecents(callingUid)) {
3616 // Always allow the recents component to get tasks
3617 return true;
3618 }
3619
3620 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3621 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3622 if (!allowed) {
3623 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3624 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3625 // Temporary compatibility: some existing apps on the system image may
3626 // still be requesting the old permission and not switched to the new
3627 // one; if so, we'll still allow them full access. This means we need
3628 // to see if they are holding the old permission and are a system app.
3629 try {
3630 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3631 allowed = true;
3632 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3633 + " is using old GET_TASKS but privileged; allowing");
3634 }
3635 } catch (RemoteException e) {
3636 }
3637 }
3638 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3639 + " does not hold REAL_GET_TASKS; limiting output");
3640 }
3641 return allowed;
3642 }
3643
Nicholas Sauer0259e532019-08-30 08:24:55 -07003644 boolean isCrossUserAllowed(int pid, int uid) {
3645 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3646 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3647 }
3648
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3650 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3651 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3652 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003653 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 "enqueueAssistContext()");
3655
3656 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003657 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 if (activity == null) {
3659 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3660 return null;
3661 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003662 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3664 return null;
3665 }
3666 if (focused) {
3667 if (activityToken != null) {
3668 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3669 if (activity != caller) {
3670 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3671 + " is not current top " + activity);
3672 return null;
3673 }
3674 }
3675 } else {
3676 activity = ActivityRecord.forTokenLocked(activityToken);
3677 if (activity == null) {
3678 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3679 + " couldn't be found");
3680 return null;
3681 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003682 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3684 return null;
3685 }
3686 }
3687
3688 PendingAssistExtras pae;
3689 Bundle extras = new Bundle();
3690 if (args != null) {
3691 extras.putAll(args);
3692 }
3693 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003694 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003695
3696 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3697 userHandle);
3698 pae.isHome = activity.isActivityTypeHome();
3699
3700 // Increment the sessionId if necessary
3701 if (newSessionId) {
3702 mViSessionId++;
3703 }
3704 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003705 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3706 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003707 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003708 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003709 } catch (RemoteException e) {
3710 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3711 return null;
3712 }
3713 return pae;
3714 }
3715 }
3716
3717 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3718 if (result != null) {
3719 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3720 }
3721 if (pae.hint != null) {
3722 pae.extras.putBoolean(pae.hint, true);
3723 }
3724 }
3725
3726 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3727 IAssistDataReceiver receiver;
3728 synchronized (mGlobalLock) {
3729 mPendingAssistExtras.remove(pae);
3730 receiver = pae.receiver;
3731 }
3732 if (receiver != null) {
3733 // Caller wants result sent back to them.
3734 Bundle sendBundle = new Bundle();
3735 // At least return the receiver extras
3736 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3737 try {
3738 pae.receiver.onHandleAssistData(sendBundle);
3739 } catch (RemoteException e) {
3740 }
3741 }
3742 }
3743
3744 public class PendingAssistExtras extends Binder implements Runnable {
3745 public final ActivityRecord activity;
3746 public boolean isHome;
3747 public final Bundle extras;
3748 public final Intent intent;
3749 public final String hint;
3750 public final IAssistDataReceiver receiver;
3751 public final int userHandle;
3752 public boolean haveResult = false;
3753 public Bundle result = null;
3754 public AssistStructure structure = null;
3755 public AssistContent content = null;
3756 public Bundle receiverExtras;
3757
3758 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3759 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3760 int _userHandle) {
3761 activity = _activity;
3762 extras = _extras;
3763 intent = _intent;
3764 hint = _hint;
3765 receiver = _receiver;
3766 receiverExtras = _receiverExtras;
3767 userHandle = _userHandle;
3768 }
3769
3770 @Override
3771 public void run() {
3772 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3773 synchronized (this) {
3774 haveResult = true;
3775 notifyAll();
3776 }
3777 pendingAssistExtrasTimedOut(this);
3778 }
3779 }
3780
3781 @Override
3782 public boolean isAssistDataAllowedOnCurrentActivity() {
3783 int userId;
3784 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003785 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3787 return false;
3788 }
3789
Wale Ogunwale21e06482019-11-18 05:14:15 -08003790 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 if (activity == null) {
3792 return false;
3793 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003794 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 }
3796 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3797 }
3798
3799 @Override
3800 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3801 long ident = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mGlobalLock) {
3804 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003805 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 if (top != caller) {
3807 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3808 + " is not current top " + top);
3809 return false;
3810 }
3811 if (!top.nowVisible) {
3812 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3813 + " is not visible");
3814 return false;
3815 }
3816 }
3817 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3818 token);
3819 } finally {
3820 Binder.restoreCallingIdentity(ident);
3821 }
3822 }
3823
3824 @Override
3825 public boolean isRootVoiceInteraction(IBinder token) {
3826 synchronized (mGlobalLock) {
3827 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3828 if (r == null) {
3829 return false;
3830 }
3831 return r.rootVoiceInteraction;
3832 }
3833 }
3834
Wale Ogunwalef6733932018-06-27 05:14:34 -07003835 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3836 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3837 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3838 if (activityToCallback == null) return;
3839 activityToCallback.setVoiceSessionLocked(voiceSession);
3840
3841 // Inform the activity
3842 try {
3843 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3844 voiceInteractor);
3845 long token = Binder.clearCallingIdentity();
3846 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003847 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003848 } finally {
3849 Binder.restoreCallingIdentity(token);
3850 }
3851 // TODO: VI Should we cache the activity so that it's easier to find later
3852 // rather than scan through all the stacks and activities?
3853 } catch (RemoteException re) {
3854 activityToCallback.clearVoiceSessionLocked();
3855 // TODO: VI Should this terminate the voice session?
3856 }
3857 }
3858
3859 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3860 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3861 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3862 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3863 boolean wasRunningVoice = mRunningVoice != null;
3864 mRunningVoice = session;
3865 if (!wasRunningVoice) {
3866 mVoiceWakeLock.acquire();
3867 updateSleepIfNeededLocked();
3868 }
3869 }
3870 }
3871
3872 void finishRunningVoiceLocked() {
3873 if (mRunningVoice != null) {
3874 mRunningVoice = null;
3875 mVoiceWakeLock.release();
3876 updateSleepIfNeededLocked();
3877 }
3878 }
3879
3880 @Override
3881 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3882 synchronized (mGlobalLock) {
3883 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3884 if (keepAwake) {
3885 mVoiceWakeLock.acquire();
3886 } else {
3887 mVoiceWakeLock.release();
3888 }
3889 }
3890 }
3891 }
3892
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 @Override
3894 public ComponentName getActivityClassForToken(IBinder token) {
3895 synchronized (mGlobalLock) {
3896 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3897 if (r == null) {
3898 return null;
3899 }
3900 return r.intent.getComponent();
3901 }
3902 }
3903
3904 @Override
3905 public String getPackageForToken(IBinder token) {
3906 synchronized (mGlobalLock) {
3907 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3908 if (r == null) {
3909 return null;
3910 }
3911 return r.packageName;
3912 }
3913 }
3914
3915 @Override
3916 public void showLockTaskEscapeMessage(IBinder token) {
3917 synchronized (mGlobalLock) {
3918 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3919 if (r == null) {
3920 return;
3921 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003922 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 }
3924 }
3925
3926 @Override
3927 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003928 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 final long token = Binder.clearCallingIdentity();
3930 try {
3931 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003932 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 }
3934 } finally {
3935 Binder.restoreCallingIdentity(token);
3936 }
3937 }
3938
3939 /**
3940 * Try to place task to provided position. The final position might be different depending on
3941 * current user and stacks state. The task will be moved to target stack if it's currently in
3942 * different stack.
3943 */
3944 @Override
3945 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003946 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947 synchronized (mGlobalLock) {
3948 long ident = Binder.clearCallingIdentity();
3949 try {
3950 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3951 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Changcdec0802019-11-11 11:45:07 +08003952 final Task task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 if (task == null) {
3954 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3955 + taskId);
3956 }
3957
Wale Ogunwaled32da472018-11-16 07:19:28 -08003958 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959
3960 if (stack == null) {
3961 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3962 + stackId);
3963 }
3964 if (!stack.isActivityTypeStandardOrUndefined()) {
3965 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3966 + " the position of task " + taskId + " in/to non-standard stack");
3967 }
3968
3969 // TODO: Have the callers of this API call a separate reparent method if that is
3970 // what they intended to do vs. having this method also do reparenting.
3971 if (task.getStack() == stack) {
3972 // Change position in current stack.
3973 stack.positionChildAt(task, position);
3974 } else {
3975 // Reparent to new stack.
3976 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3977 !DEFER_RESUME, "positionTaskInStack");
3978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(ident);
3981 }
3982 }
3983 }
3984
3985 @Override
3986 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3987 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3988 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003989 + Arrays.toString(horizontalSizeConfiguration) + " "
3990 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003991 synchronized (mGlobalLock) {
3992 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3993 if (record == null) {
3994 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3995 + "found for: " + token);
3996 }
3997 record.setSizeConfigurations(horizontalSizeConfiguration,
3998 verticalSizeConfigurations, smallestSizeConfigurations);
3999 }
4000 }
4001
4002 /**
4003 * Dismisses split-screen multi-window mode.
4004 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4005 */
4006 @Override
4007 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004008 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004009 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4010 final long ident = Binder.clearCallingIdentity();
4011 try {
4012 synchronized (mGlobalLock) {
4013 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004014 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 if (stack == null) {
4016 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4017 return;
4018 }
4019
4020 if (toTop) {
4021 // Caller wants the current split-screen primary stack to be the top stack after
4022 // it goes fullscreen, so move it to the front.
4023 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004024 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004026 // stack after it goes fullscreen, so we move the focus to the top-most
4027 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4029 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4030 if (otherStack != null) {
4031 otherStack.moveToFront("dismissSplitScreenMode_other");
4032 }
4033 }
4034
Evan Rosky10475742018-09-05 19:02:48 -07004035 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 }
4037 } finally {
4038 Binder.restoreCallingIdentity(ident);
4039 }
4040 }
4041
4042 /**
4043 * Dismisses Pip
4044 * @param animate True if the dismissal should be animated.
4045 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4046 * default animation duration should be used.
4047 */
4048 @Override
4049 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 final long ident = Binder.clearCallingIdentity();
4052 try {
4053 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004054 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004055 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 if (stack == null) {
4057 Slog.w(TAG, "dismissPip: pinned stack not found.");
4058 return;
4059 }
4060 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4061 throw new IllegalArgumentException("Stack: " + stack
4062 + " doesn't support animated resize.");
4063 }
4064 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004065 stack.animateResizePinnedStack(null /* destBounds */,
4066 null /* sourceHintBounds */, animationDuration,
4067 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004069 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004070 }
4071 }
4072 } finally {
4073 Binder.restoreCallingIdentity(ident);
4074 }
4075 }
4076
4077 @Override
4078 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004079 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 synchronized (mGlobalLock) {
4081 mSuppressResizeConfigChanges = suppress;
4082 }
4083 }
4084
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 @Override
4086 // TODO: API should just be about changing windowing modes...
4087 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004088 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 "moveTasksToFullscreenStack()");
4090 synchronized (mGlobalLock) {
4091 final long origId = Binder.clearCallingIdentity();
4092 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004093 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 if (stack != null){
4095 if (!stack.isActivityTypeStandardOrUndefined()) {
4096 throw new IllegalArgumentException(
4097 "You can't move tasks from non-standard stacks.");
4098 }
4099 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4100 }
4101 } finally {
4102 Binder.restoreCallingIdentity(origId);
4103 }
4104 }
4105 }
4106
4107 /**
4108 * Moves the top activity in the input stackId to the pinned stack.
4109 *
4110 * @param stackId Id of stack to move the top activity to pinned stack.
4111 * @param bounds Bounds to use for pinned stack.
4112 *
4113 * @return True if the top activity of the input stack was successfully moved to the pinned
4114 * stack.
4115 */
4116 @Override
4117 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004118 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 "moveTopActivityToPinnedStack()");
4120 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004121 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4123 + "Device doesn't support picture-in-picture mode");
4124 }
4125
4126 long ident = Binder.clearCallingIdentity();
4127 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004128 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 } finally {
4130 Binder.restoreCallingIdentity(ident);
4131 }
4132 }
4133 }
4134
4135 @Override
4136 public boolean isInMultiWindowMode(IBinder token) {
4137 final long origId = Binder.clearCallingIdentity();
4138 try {
4139 synchronized (mGlobalLock) {
4140 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4141 if (r == null) {
4142 return false;
4143 }
4144 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4145 return r.inMultiWindowMode();
4146 }
4147 } finally {
4148 Binder.restoreCallingIdentity(origId);
4149 }
4150 }
4151
4152 @Override
4153 public boolean isInPictureInPictureMode(IBinder token) {
4154 final long origId = Binder.clearCallingIdentity();
4155 try {
4156 synchronized (mGlobalLock) {
4157 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4158 }
4159 } finally {
4160 Binder.restoreCallingIdentity(origId);
4161 }
4162 }
4163
4164 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004165 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4166 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 return false;
4168 }
4169
4170 // If we are animating to fullscreen then we have already dispatched the PIP mode
4171 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004172 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004173 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 }
4175
4176 @Override
4177 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4178 final long origId = Binder.clearCallingIdentity();
4179 try {
4180 synchronized (mGlobalLock) {
4181 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4182 "enterPictureInPictureMode", token, params);
4183
4184 // If the activity is already in picture in picture mode, then just return early
4185 if (isInPictureInPictureMode(r)) {
4186 return true;
4187 }
4188
4189 // Activity supports picture-in-picture, now check that we can enter PiP at this
4190 // point, if it is
4191 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4192 false /* beforeStopping */)) {
4193 return false;
4194 }
4195
4196 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004197 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004198 if (r.getParent() == null) {
4199 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4200 return;
4201 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004202 // Only update the saved args from the args that are set
4203 r.pictureInPictureArgs.copyOnlySet(params);
4204 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4205 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4206 // Adjust the source bounds by the insets for the transition down
4207 final Rect sourceBounds = new Rect(
4208 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004209 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004210 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004211 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004212 stack.setPictureInPictureAspectRatio(aspectRatio);
4213 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004214 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4215 r.info.applicationInfo.uid, r.shortComponentName,
4216 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004217 logPictureInPictureArgs(params);
4218 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 };
4220
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004221 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 // If the keyguard is showing or occluded, then try and dismiss it before
4223 // entering picture-in-picture (this will prompt the user to authenticate if the
4224 // device is currently locked).
4225 dismissKeyguard(token, new KeyguardDismissCallback() {
4226 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004227 public void onDismissSucceeded() {
4228 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 }
4230 }, null /* message */);
4231 } else {
4232 // Enter picture in picture immediately otherwise
4233 enterPipRunnable.run();
4234 }
4235 return true;
4236 }
4237 } finally {
4238 Binder.restoreCallingIdentity(origId);
4239 }
4240 }
4241
4242 @Override
4243 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4244 final long origId = Binder.clearCallingIdentity();
4245 try {
4246 synchronized (mGlobalLock) {
4247 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4248 "setPictureInPictureParams", token, params);
4249
4250 // Only update the saved args from the args that are set
4251 r.pictureInPictureArgs.copyOnlySet(params);
4252 if (r.inPinnedWindowingMode()) {
4253 // If the activity is already in picture-in-picture, update the pinned stack now
4254 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4255 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004256 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004257 if (!stack.isAnimatingBoundsToFullscreen()) {
4258 stack.setPictureInPictureAspectRatio(
4259 r.pictureInPictureArgs.getAspectRatio());
4260 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4261 }
4262 }
4263 logPictureInPictureArgs(params);
4264 }
4265 } finally {
4266 Binder.restoreCallingIdentity(origId);
4267 }
4268 }
4269
4270 @Override
4271 public int getMaxNumPictureInPictureActions(IBinder token) {
4272 // Currently, this is a static constant, but later, we may change this to be dependent on
4273 // the context of the activity
4274 return 3;
4275 }
4276
4277 private void logPictureInPictureArgs(PictureInPictureParams params) {
4278 if (params.hasSetActions()) {
4279 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4280 params.getActions().size());
4281 }
4282 if (params.hasSetAspectRatio()) {
4283 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4284 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4285 MetricsLogger.action(lm);
4286 }
4287 }
4288
4289 /**
4290 * Checks the state of the system and the activity associated with the given {@param token} to
4291 * verify that picture-in-picture is supported for that activity.
4292 *
4293 * @return the activity record for the given {@param token} if all the checks pass.
4294 */
4295 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4296 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 throw new IllegalStateException(caller
4299 + ": Device doesn't support picture-in-picture mode.");
4300 }
4301
4302 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4303 if (r == null) {
4304 throw new IllegalStateException(caller
4305 + ": Can't find activity for token=" + token);
4306 }
4307
4308 if (!r.supportsPictureInPicture()) {
4309 throw new IllegalStateException(caller
4310 + ": Current activity does not support picture-in-picture.");
4311 }
4312
4313 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004314 && !mWindowManager.isValidPictureInPictureAspectRatio(
4315 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 final float minAspectRatio = mContext.getResources().getFloat(
4317 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4318 final float maxAspectRatio = mContext.getResources().getFloat(
4319 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4320 throw new IllegalArgumentException(String.format(caller
4321 + ": Aspect ratio is too extreme (must be between %f and %f).",
4322 minAspectRatio, maxAspectRatio));
4323 }
4324
4325 // Truncate the number of actions if necessary
4326 params.truncateActions(getMaxNumPictureInPictureActions(token));
4327
4328 return r;
4329 }
4330
4331 @Override
4332 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004333 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 synchronized (mGlobalLock) {
4335 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4336 if (r == null) {
4337 throw new IllegalArgumentException("Activity does not exist; token="
4338 + activityToken);
4339 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004340 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004341 }
4342 }
4343
4344 @Override
4345 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4346 Rect tempDockedTaskInsetBounds,
4347 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004348 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 long ident = Binder.clearCallingIdentity();
4350 try {
4351 synchronized (mGlobalLock) {
4352 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4353 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4354 PRESERVE_WINDOWS);
4355 }
4356 } finally {
4357 Binder.restoreCallingIdentity(ident);
4358 }
4359 }
4360
4361 @Override
4362 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004363 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 final long ident = Binder.clearCallingIdentity();
4365 try {
4366 synchronized (mGlobalLock) {
4367 mStackSupervisor.setSplitScreenResizing(resizing);
4368 }
4369 } finally {
4370 Binder.restoreCallingIdentity(ident);
4371 }
4372 }
4373
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 /**
4375 * Check that we have the features required for VR-related API calls, and throw an exception if
4376 * not.
4377 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004378 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 if (!mContext.getPackageManager().hasSystemFeature(
4380 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4381 throw new UnsupportedOperationException("VR mode not supported on this device!");
4382 }
4383 }
4384
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 @Override
4386 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388
4389 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4390
4391 ActivityRecord r;
4392 synchronized (mGlobalLock) {
4393 r = ActivityRecord.isInStackLocked(token);
4394 }
4395
4396 if (r == null) {
4397 throw new IllegalArgumentException();
4398 }
4399
4400 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004401 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 VrManagerInternal.NO_ERROR) {
4403 return err;
4404 }
4405
4406 // Clear the binder calling uid since this path may call moveToTask().
4407 final long callingId = Binder.clearCallingIdentity();
4408 try {
4409 synchronized (mGlobalLock) {
4410 r.requestedVrComponent = (enabled) ? packageName : null;
4411
4412 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004413 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004414 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 }
4416 return 0;
4417 }
4418 } finally {
4419 Binder.restoreCallingIdentity(callingId);
4420 }
4421 }
4422
4423 @Override
4424 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4425 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4426 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004427 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4429 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4430 }
Louis Changcdec0802019-11-11 11:45:07 +08004431 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 || activity.voiceSession != null) {
4433 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4434 return;
4435 }
4436 if (activity.pendingVoiceInteractionStart) {
4437 Slog.w(TAG, "Pending start of voice interaction already.");
4438 return;
4439 }
4440 activity.pendingVoiceInteractionStart = true;
4441 }
4442 LocalServices.getService(VoiceInteractionManagerInternal.class)
4443 .startLocalVoiceInteraction(callingActivity, options);
4444 }
4445
4446 @Override
4447 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4448 LocalServices.getService(VoiceInteractionManagerInternal.class)
4449 .stopLocalVoiceInteraction(callingActivity);
4450 }
4451
4452 @Override
4453 public boolean supportsLocalVoiceInteraction() {
4454 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4455 .supportsLocalVoiceInteraction();
4456 }
4457
4458 /** Notifies all listeners when the pinned stack animation starts. */
4459 @Override
4460 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004461 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 }
4463
4464 /** Notifies all listeners when the pinned stack animation ends. */
4465 @Override
4466 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004467 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 }
4469
4470 @Override
4471 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473 final long ident = Binder.clearCallingIdentity();
4474 try {
4475 synchronized (mGlobalLock) {
4476 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4477 }
4478 } finally {
4479 Binder.restoreCallingIdentity(ident);
4480 }
4481 }
4482
4483 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004484 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004485 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004486
4487 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004488 if (mWindowManager == null) {
4489 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4490 return false;
4491 }
4492
4493 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004494 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496 }
4497
Riddle Hsua0022cd2019-09-09 21:12:41 +08004498 mH.sendMessage(PooledLambda.obtainMessage(
4499 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4500 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501
4502 final long origId = Binder.clearCallingIdentity();
4503 try {
4504 if (values != null) {
4505 Settings.System.clearConfiguration(values);
4506 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004507 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 UserHandle.USER_NULL, false /* deferResume */,
4509 mTmpUpdateConfigurationResult);
4510 return mTmpUpdateConfigurationResult.changes != 0;
4511 } finally {
4512 Binder.restoreCallingIdentity(origId);
4513 }
4514 }
4515 }
4516
4517 @Override
4518 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4519 CharSequence message) {
4520 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004521 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4523 }
4524 final long callingId = Binder.clearCallingIdentity();
4525 try {
4526 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004527 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004528 }
4529 } finally {
4530 Binder.restoreCallingIdentity(callingId);
4531 }
4532 }
4533
4534 @Override
4535 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004536 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004537 "cancelTaskWindowTransition()");
4538 final long ident = Binder.clearCallingIdentity();
4539 try {
4540 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08004541 final Task task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004542 MATCH_TASK_IN_STACKS_ONLY);
4543 if (task == null) {
4544 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4545 return;
4546 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004547 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004548 }
4549 } finally {
4550 Binder.restoreCallingIdentity(ident);
4551 }
4552 }
4553
4554 @Override
4555 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004556 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 final long ident = Binder.clearCallingIdentity();
4558 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004559 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004560 } finally {
4561 Binder.restoreCallingIdentity(ident);
4562 }
4563 }
4564
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004565 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4566 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004567 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004568 synchronized (mGlobalLock) {
4569 task = mRootActivityContainer.anyTaskForId(taskId,
4570 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4571 if (task == null) {
4572 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4573 return null;
4574 }
4575 }
4576 // Don't call this while holding the lock as this operation might hit the disk.
4577 return task.getSnapshot(reducedResolution, restoreFromDisk);
4578 }
4579
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004580 @Override
4581 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4582 synchronized (mGlobalLock) {
4583 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4584 if (r == null) {
4585 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4586 + token);
4587 return;
4588 }
4589 final long origId = Binder.clearCallingIdentity();
4590 try {
4591 r.setDisablePreviewScreenshots(disable);
4592 } finally {
4593 Binder.restoreCallingIdentity(origId);
4594 }
4595 }
4596 }
4597
Riddle Hsu440f88b2019-11-06 22:17:35 +08004598 @Override
4599 public void invalidateHomeTaskSnapshot(IBinder token) {
4600 synchronized (mGlobalLock) {
4601 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4602 if (r == null || !r.isActivityTypeHome()) {
4603 return;
4604 }
4605 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4606 }
4607 }
4608
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 /** Return the user id of the last resumed activity. */
4610 @Override
4611 public @UserIdInt
4612 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004613 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004614 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4615 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004616 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004617 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004618 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004619 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004620 }
4621 }
4622
4623 @Override
4624 public void updateLockTaskFeatures(int userId, int flags) {
4625 final int callingUid = Binder.getCallingUid();
4626 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004627 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004628 "updateLockTaskFeatures()");
4629 }
4630 synchronized (mGlobalLock) {
4631 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4632 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004633 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004634 }
4635 }
4636
4637 @Override
4638 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4639 synchronized (mGlobalLock) {
4640 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4641 if (r == null) {
4642 return;
4643 }
4644 final long origId = Binder.clearCallingIdentity();
4645 try {
4646 r.setShowWhenLocked(showWhenLocked);
4647 } finally {
4648 Binder.restoreCallingIdentity(origId);
4649 }
4650 }
4651 }
4652
4653 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004654 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4655 synchronized (mGlobalLock) {
4656 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4657 if (r == null) {
4658 return;
4659 }
4660 final long origId = Binder.clearCallingIdentity();
4661 try {
4662 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4663 } finally {
4664 Binder.restoreCallingIdentity(origId);
4665 }
4666 }
4667 }
4668
4669 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004670 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4671 synchronized (mGlobalLock) {
4672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4673 if (r == null) {
4674 return;
4675 }
4676 final long origId = Binder.clearCallingIdentity();
4677 try {
4678 r.setTurnScreenOn(turnScreenOn);
4679 } finally {
4680 Binder.restoreCallingIdentity(origId);
4681 }
4682 }
4683 }
4684
4685 @Override
4686 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004689 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004690 synchronized (mGlobalLock) {
4691 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4692 if (r == null) {
4693 return;
4694 }
4695 final long origId = Binder.clearCallingIdentity();
4696 try {
4697 r.registerRemoteAnimations(definition);
4698 } finally {
4699 Binder.restoreCallingIdentity(origId);
4700 }
4701 }
4702 }
4703
4704 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004705 public void unregisterRemoteAnimations(IBinder token) {
4706 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4707 "unregisterRemoteAnimations");
4708 synchronized (mGlobalLock) {
4709 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4710 if (r == null) {
4711 return;
4712 }
4713 final long origId = Binder.clearCallingIdentity();
4714 try {
4715 r.unregisterRemoteAnimations();
4716 } finally {
4717 Binder.restoreCallingIdentity(origId);
4718 }
4719 }
4720 }
4721
4722 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004723 public void registerRemoteAnimationForNextActivityStart(String packageName,
4724 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004725 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004726 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004727 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004728 synchronized (mGlobalLock) {
4729 final long origId = Binder.clearCallingIdentity();
4730 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004731 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004732 packageName, adapter);
4733 } finally {
4734 Binder.restoreCallingIdentity(origId);
4735 }
4736 }
4737 }
4738
Evan Rosky966759f2019-01-15 10:33:58 -08004739 @Override
4740 public void registerRemoteAnimationsForDisplay(int displayId,
4741 RemoteAnimationDefinition definition) {
4742 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4743 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004744 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004745 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08004746 final DisplayContent display = mRootActivityContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004747 if (display == null) {
4748 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4749 return;
4750 }
4751 final long origId = Binder.clearCallingIdentity();
4752 try {
4753 display.mDisplayContent.registerRemoteAnimations(definition);
4754 } finally {
4755 Binder.restoreCallingIdentity(origId);
4756 }
4757 }
4758 }
4759
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004760 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4761 @Override
4762 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4763 synchronized (mGlobalLock) {
4764 final long origId = Binder.clearCallingIdentity();
4765 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004766 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004767 } finally {
4768 Binder.restoreCallingIdentity(origId);
4769 }
4770 }
4771 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004772
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004773 @Override
4774 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004775 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004776 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004777 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004778 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004779 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 }
4781 }
4782
4783 @Override
4784 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004785 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004786 != PERMISSION_GRANTED) {
4787 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4788 + Binder.getCallingPid()
4789 + ", uid=" + Binder.getCallingUid()
4790 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4791 Slog.w(TAG, msg);
4792 throw new SecurityException(msg);
4793 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004794 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004796 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004797 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004798 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 }
4800 }
4801
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004802 @Override
4803 public void stopAppSwitches() {
4804 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4805 synchronized (mGlobalLock) {
4806 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004807 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004808 mDidAppSwitch = false;
4809 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4810 }
4811 }
4812
4813 @Override
4814 public void resumeAppSwitches() {
4815 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4816 synchronized (mGlobalLock) {
4817 // Note that we don't execute any pending app switches... we will
4818 // let those wait until either the timeout, or the next start
4819 // activity request.
4820 mAppSwitchesAllowedTime = 0;
4821 }
4822 }
4823
Ricky Wai906af482019-06-03 17:25:28 +01004824 long getLastStopAppSwitchesTime() {
4825 return mLastStopAppSwitchesTime;
4826 }
4827
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004828 void onStartActivitySetDidAppSwitch() {
4829 if (mDidAppSwitch) {
4830 // This is the second allowed switch since we stopped switches, so now just generally
4831 // allow switches. Use case:
4832 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4833 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4834 // anyone to switch again).
4835 mAppSwitchesAllowedTime = 0;
4836 } else {
4837 mDidAppSwitch = true;
4838 }
4839 }
4840
4841 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004842 boolean shouldDisableNonVrUiLocked() {
4843 return mVrController.shouldDisableNonVrUiLocked();
4844 }
4845
Wale Ogunwale53783742018-09-16 10:21:51 -07004846 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004847 // 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 +00004848 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004849 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004850 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4851 + " to main display for VR");
4852 mRootActivityContainer.moveStackToDisplay(
4853 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004854 }
4855 mH.post(() -> {
4856 if (!mVrController.onVrModeChanged(r)) {
4857 return;
4858 }
4859 synchronized (mGlobalLock) {
4860 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4861 mWindowManager.disableNonVrUi(disableNonVrUi);
4862 if (disableNonVrUi) {
4863 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4864 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004865 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004866 }
4867 }
4868 });
4869 }
4870
Wale Ogunwale53783742018-09-16 10:21:51 -07004871 @Override
4872 public int getPackageScreenCompatMode(String packageName) {
4873 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4874 synchronized (mGlobalLock) {
4875 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4876 }
4877 }
4878
4879 @Override
4880 public void setPackageScreenCompatMode(String packageName, int mode) {
4881 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4882 "setPackageScreenCompatMode");
4883 synchronized (mGlobalLock) {
4884 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4885 }
4886 }
4887
4888 @Override
4889 public boolean getPackageAskScreenCompat(String packageName) {
4890 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4891 synchronized (mGlobalLock) {
4892 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4893 }
4894 }
4895
4896 @Override
4897 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4898 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4899 "setPackageAskScreenCompat");
4900 synchronized (mGlobalLock) {
4901 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4902 }
4903 }
4904
Wale Ogunwale64258362018-10-16 15:13:37 -07004905 public static String relaunchReasonToString(int relaunchReason) {
4906 switch (relaunchReason) {
4907 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4908 return "window_resize";
4909 case RELAUNCH_REASON_FREE_RESIZE:
4910 return "free_resize";
4911 default:
4912 return null;
4913 }
4914 }
4915
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004916 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004917 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004918 }
4919
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004920 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004921 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004922 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4923 }
4924
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004925 boolean isKeyguardLocked() {
4926 return mKeyguardController.isKeyguardLocked();
4927 }
4928
Garfield Tan01548632018-11-27 10:15:48 -08004929 /**
4930 * Clears launch params for the given package.
4931 * @param packageNames the names of the packages of which the launch params are to be cleared
4932 */
4933 @Override
4934 public void clearLaunchParamsForPackages(List<String> packageNames) {
4935 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4936 "clearLaunchParamsForPackages");
4937 synchronized (mGlobalLock) {
4938 for (int i = 0; i < packageNames.size(); ++i) {
4939 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4940 }
4941 }
4942 }
4943
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004944 /**
4945 * Makes the display with the given id a single task instance display. I.e the display can only
4946 * contain one task.
4947 */
4948 @Override
4949 public void setDisplayToSingleTaskInstance(int displayId) {
4950 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4951 "setDisplayToSingleTaskInstance");
4952 final long origId = Binder.clearCallingIdentity();
4953 try {
Louis Chang677921f2019-12-06 16:44:24 +08004954 final DisplayContent display =
4955 mRootActivityContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004956 if (display != null) {
4957 display.setDisplayToSingleTaskInstance();
4958 }
4959 } finally {
4960 Binder.restoreCallingIdentity(origId);
4961 }
4962 }
4963
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004964 /**
4965 * Requests that an activity should enter picture-in-picture mode if possible.
4966 */
4967 @Override
4968 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4969 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4970 "requestPictureInPictureMode");
4971 final long origId = Binder.clearCallingIdentity();
4972 try {
4973 synchronized (mGlobalLock) {
4974 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4975 if (activity == null) {
4976 return;
4977 }
4978
4979 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4980 "requestPictureInPictureMode", /* beforeStopping */ false);
4981 if (!canEnterPictureInPicture) {
4982 throw new IllegalStateException(
4983 "Requested PIP on an activity that doesn't support it");
4984 }
4985
4986 try {
4987 final ClientTransaction transaction = ClientTransaction.obtain(
4988 activity.app.getThread(),
4989 activity.token);
4990 transaction.addCallback(EnterPipRequestedItem.obtain());
4991 getLifecycleManager().scheduleTransaction(transaction);
4992 } catch (Exception e) {
4993 Slog.w(TAG, "Failed to send enter pip requested item: "
4994 + activity.intent.getComponent(), e);
4995 }
4996 }
4997 } finally {
4998 Binder.restoreCallingIdentity(origId);
4999 }
5000 }
5001
Wale Ogunwale31913b52018-10-13 08:29:31 -07005002 void dumpLastANRLocked(PrintWriter pw) {
5003 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5004 if (mLastANRState == null) {
5005 pw.println(" <no ANR has occurred since boot>");
5006 } else {
5007 pw.println(mLastANRState);
5008 }
5009 }
5010
5011 void dumpLastANRTracesLocked(PrintWriter pw) {
5012 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5013
5014 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5015 if (ArrayUtils.isEmpty(files)) {
5016 pw.println(" <no ANR has occurred since boot>");
5017 return;
5018 }
5019 // Find the latest file.
5020 File latest = null;
5021 for (File f : files) {
5022 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5023 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005024 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005025 }
5026 pw.print("File: ");
5027 pw.print(latest.getName());
5028 pw.println();
5029 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5030 String line;
5031 while ((line = in.readLine()) != null) {
5032 pw.println(line);
5033 }
5034 } catch (IOException e) {
5035 pw.print("Unable to read: ");
5036 pw.print(e);
5037 pw.println();
5038 }
5039 }
5040
5041 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5042 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5043 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5044 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5045 }
5046
5047 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5048 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5049 pw.println(header);
5050
Wale Ogunwaled32da472018-11-16 07:19:28 -08005051 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005052 dumpPackage);
5053 boolean needSep = printedAnything;
5054
5055 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08005056 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005057 " ResumedActivity: ");
5058 if (printed) {
5059 printedAnything = true;
5060 needSep = false;
5061 }
5062
5063 if (dumpPackage == null) {
5064 if (needSep) {
5065 pw.println();
5066 }
5067 printedAnything = true;
5068 mStackSupervisor.dump(pw, " ");
5069 }
5070
5071 if (!printedAnything) {
5072 pw.println(" (nothing)");
5073 }
5074 }
5075
5076 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005077 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08005078 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005079 pw.println(" ");
5080 }
5081
5082 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5083 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5084 getActivityStartController().dump(pw, "", dumpPackage);
5085 }
5086
5087 /**
5088 * There are three things that cmd can be:
5089 * - a flattened component name that matches an existing activity
5090 * - the cmd arg isn't the flattened component name of an existing activity:
5091 * dump all activity whose component contains the cmd as a substring
5092 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005093 * <p>
5094 * The caller should not hold lock when calling this method because it will wait for the
5095 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005096 *
5097 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5098 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5099 */
5100 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5101 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5102 ArrayList<ActivityRecord> activities;
5103
5104 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005105 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005106 dumpFocusedStackOnly);
5107 }
5108
5109 if (activities.size() <= 0) {
5110 return false;
5111 }
5112
5113 String[] newArgs = new String[args.length - opti];
5114 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5115
Louis Changcdec0802019-11-11 11:45:07 +08005116 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005117 boolean needSep = false;
5118 for (int i = activities.size() - 1; i >= 0; i--) {
5119 ActivityRecord r = activities.get(i);
5120 if (needSep) {
5121 pw.println();
5122 }
5123 needSep = true;
5124 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005125 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005126 if (lastTask != task) {
5127 lastTask = task;
5128 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005129 pw.print(" id="); pw.print(lastTask.mTaskId);
5130 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005131 if (dumpAll) {
5132 lastTask.dump(pw, " ");
5133 }
5134 }
5135 }
5136 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5137 }
5138 return true;
5139 }
5140
5141 /**
5142 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5143 * there is a thread associated with the activity.
5144 */
5145 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5146 final ActivityRecord r, String[] args, boolean dumpAll) {
5147 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005148 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005149 synchronized (mGlobalLock) {
5150 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5151 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5152 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005153 if (r.hasProcess()) {
5154 pw.println(r.app.getPid());
5155 appThread = r.app.getThread();
5156 } else {
5157 pw.println("(not running)");
5158 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005159 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005160 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005161 }
5162 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005163 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005164 // flush anything that is already in the PrintWriter since the thread is going
5165 // to write to the file descriptor directly
5166 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005167 try (TransferPipe tp = new TransferPipe()) {
5168 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5169 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005170 } catch (IOException e) {
5171 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5172 } catch (RemoteException e) {
5173 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5174 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005175 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005176 }
5177
sanryhuang498e77e2018-12-06 14:57:01 +08005178 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5179 boolean testPssMode) {
5180 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5181 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5182 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005183 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005184 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5185 st.toString());
5186 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005187 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5188 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5189 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005190 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5191 testPssMode);
5192 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005193 }
5194
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005195 int getCurrentUserId() {
5196 return mAmInternal.getCurrentUserId();
5197 }
5198
5199 private void enforceNotIsolatedCaller(String caller) {
5200 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5201 throw new SecurityException("Isolated process not allowed to call " + caller);
5202 }
5203 }
5204
Wale Ogunwalef6733932018-06-27 05:14:34 -07005205 public Configuration getConfiguration() {
5206 Configuration ci;
5207 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005208 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005209 ci.userSetLocale = false;
5210 }
5211 return ci;
5212 }
5213
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005214 /**
5215 * Current global configuration information. Contains general settings for the entire system,
5216 * also corresponds to the merged configuration of the default display.
5217 */
5218 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005219 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005220 }
5221
5222 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5223 boolean initLocale) {
5224 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5225 }
5226
5227 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5228 boolean initLocale, boolean deferResume) {
5229 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5230 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5231 UserHandle.USER_NULL, deferResume);
5232 }
5233
Wale Ogunwale59507092018-10-29 09:00:30 -07005234 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235 final long origId = Binder.clearCallingIdentity();
5236 try {
5237 synchronized (mGlobalLock) {
5238 updateConfigurationLocked(values, null, false, true, userId,
5239 false /* deferResume */);
5240 }
5241 } finally {
5242 Binder.restoreCallingIdentity(origId);
5243 }
5244 }
5245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5247 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5248 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5249 deferResume, null /* result */);
5250 }
5251
5252 /**
5253 * Do either or both things: (1) change the current configuration, and (2)
5254 * make sure the given activity is running with the (now) current
5255 * configuration. Returns true if the activity has been left running, or
5256 * false if <var>starting</var> is being destroyed to match the new
5257 * configuration.
5258 *
5259 * @param userId is only used when persistent parameter is set to true to persist configuration
5260 * for that particular user
5261 */
5262 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5263 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5264 ActivityTaskManagerService.UpdateConfigurationResult result) {
5265 int changes = 0;
5266 boolean kept = true;
5267
Riddle Hsua0022cd2019-09-09 21:12:41 +08005268 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269 try {
5270 if (values != null) {
5271 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5272 deferResume);
5273 }
5274
5275 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5276 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005277 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 }
5279
5280 if (result != null) {
5281 result.changes = changes;
5282 result.activityRelaunched = !kept;
5283 }
5284 return kept;
5285 }
5286
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005288 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005290
Louis Chang677921f2019-12-06 16:44:24 +08005291 final DisplayContent defaultDisplay =
5292 mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005293
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 mTempConfig.setTo(getGlobalConfiguration());
5295 final int changes = mTempConfig.updateFrom(values);
5296 if (changes == 0) {
5297 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5298 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5299 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5300 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005301 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005302 return 0;
5303 }
5304
5305 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5306 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005307 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005308 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5309 values.colorMode,
5310 values.densityDpi,
5311 values.fontScale,
5312 values.hardKeyboardHidden,
5313 values.keyboard,
5314 values.keyboardHidden,
5315 values.mcc,
5316 values.mnc,
5317 values.navigation,
5318 values.navigationHidden,
5319 values.orientation,
5320 values.screenHeightDp,
5321 values.screenLayout,
5322 values.screenWidthDp,
5323 values.smallestScreenWidthDp,
5324 values.touchscreen,
5325 values.uiMode);
5326
5327
5328 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5329 final LocaleList locales = values.getLocales();
5330 int bestLocaleIndex = 0;
5331 if (locales.size() > 1) {
5332 if (mSupportedSystemLocales == null) {
5333 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5334 }
5335 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5336 }
5337 SystemProperties.set("persist.sys.locale",
5338 locales.get(bestLocaleIndex).toLanguageTag());
5339 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005340
5341 final Message m = PooledLambda.obtainMessage(
5342 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5343 locales.get(bestLocaleIndex));
5344 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005345 }
5346
Yunfan Chen75157d72018-07-27 14:47:21 +09005347 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005348
5349 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005350 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005351
5352 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5353 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005354 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005355
5356 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005357 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005358
5359 AttributeCache ac = AttributeCache.instance();
5360 if (ac != null) {
5361 ac.updateConfiguration(mTempConfig);
5362 }
5363
5364 // Make sure all resources in our process are updated right now, so that anyone who is going
5365 // to retrieve resource values after we return will be sure to get the new ones. This is
5366 // especially important during boot, where the first config change needs to guarantee all
5367 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005368 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005369
5370 // We need another copy of global config because we're scheduling some calls instead of
5371 // running them in place. We need to be sure that object we send will be handled unchanged.
5372 final Configuration configCopy = new Configuration(mTempConfig);
5373 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005374 final Message msg = PooledLambda.obtainMessage(
5375 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5376 this, userId, configCopy);
5377 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005378 }
5379
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005380 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5381 for (int i = pidMap.size() - 1; i >= 0; i--) {
5382 final int pid = pidMap.keyAt(i);
5383 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005384 if (DEBUG_CONFIGURATION) {
5385 Slog.v(TAG_CONFIGURATION, "Update process config of "
5386 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005387 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005388 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005389 }
5390
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005391 final Message msg = PooledLambda.obtainMessage(
5392 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5393 mAmInternal, changes, initLocale);
5394 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005395
5396 // Override configuration of the default display duplicates global config, so we need to
5397 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005398 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5399 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005400
5401 return changes;
5402 }
5403
Riddle Hsua0022cd2019-09-09 21:12:41 +08005404 /** @see WindowSurfacePlacer#deferLayout */
5405 void deferWindowLayout() {
5406 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5407 // Reset the reasons at the first entrance because we only care about the changes in the
5408 // deferred scope.
5409 mLayoutReasons = 0;
5410 }
5411
5412 mWindowManager.mWindowPlacerLocked.deferLayout();
5413 }
5414
5415 /** @see WindowSurfacePlacer#continueLayout */
5416 void continueWindowLayout() {
5417 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5418 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5419 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5420 }
5421 }
5422
5423 /**
5424 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5425 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5426 * defer count is gone.
5427 */
5428 void addWindowLayoutReasons(@LayoutReason int reasons) {
5429 mLayoutReasons |= reasons;
5430 }
5431
Wale Ogunwalef6733932018-06-27 05:14:34 -07005432 private void updateEventDispatchingLocked(boolean booted) {
5433 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5434 }
5435
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005436 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5437 final ContentResolver resolver = mContext.getContentResolver();
5438 Settings.System.putConfigurationForUser(resolver, config, userId);
5439 }
5440
5441 private void sendLocaleToMountDaemonMsg(Locale l) {
5442 try {
5443 IBinder service = ServiceManager.getService("mount");
5444 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5445 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5446 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5447 } catch (RemoteException e) {
5448 Log.e(TAG, "Error storing locale for decryption UI", e);
5449 }
5450 }
5451
Alison Cichowlas3e340502018-08-07 17:15:01 -04005452 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5453 mStartActivitySources.remove(permissionToken);
5454 mExpiredStartAsCallerTokens.add(permissionToken);
5455 }
5456
5457 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5458 mExpiredStartAsCallerTokens.remove(permissionToken);
5459 }
5460
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005461 boolean isActivityStartsLoggingEnabled() {
5462 return mAmInternal.isActivityStartsLoggingEnabled();
5463 }
5464
Michal Karpinski8596ded2018-11-14 14:43:48 +00005465 boolean isBackgroundActivityStartsEnabled() {
5466 return mAmInternal.isBackgroundActivityStartsEnabled();
5467 }
5468
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005470 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005471 mWindowManager.enableScreenAfterBoot();
5472
5473 synchronized (mGlobalLock) {
5474 updateEventDispatchingLocked(booted);
5475 }
5476 }
5477
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005478 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5479 if (r == null || !r.hasProcess()) {
5480 return KEY_DISPATCHING_TIMEOUT_MS;
5481 }
5482 return getInputDispatchingTimeoutLocked(r.app);
5483 }
5484
5485 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005486 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005487 }
5488
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 /**
5490 * Decide based on the configuration whether we should show the ANR,
5491 * crash, etc dialogs. The idea is that if there is no affordance to
5492 * press the on-screen buttons, or the user experience would be more
5493 * greatly impacted than the crash itself, we shouldn't show the dialog.
5494 *
5495 * A thought: SystemUI might also want to get told about this, the Power
5496 * dialog / global actions also might want different behaviors.
5497 */
5498 private void updateShouldShowDialogsLocked(Configuration config) {
5499 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5500 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5501 && config.navigation == Configuration.NAVIGATION_NONAV);
5502 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5503 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5504 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5505 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5506 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5507 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5508 HIDE_ERROR_DIALOGS, 0) != 0;
5509 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5510 }
5511
5512 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5513 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5514 FONT_SCALE, 1.0f, userId);
5515
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005516 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 if (getGlobalConfiguration().fontScale == scaleFactor) {
5518 return;
5519 }
5520
5521 final Configuration configuration
5522 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5523 configuration.fontScale = scaleFactor;
5524 updatePersistentConfiguration(configuration, userId);
5525 }
5526 }
5527
5528 // Actually is sleeping or shutting down or whatever else in the future
5529 // is an inactive state.
5530 boolean isSleepingOrShuttingDownLocked() {
5531 return isSleepingLocked() || mShuttingDown;
5532 }
5533
5534 boolean isSleepingLocked() {
5535 return mSleeping;
5536 }
5537
Riddle Hsu16567132018-08-16 21:37:47 +08005538 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005540 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541 if (task.isActivityTypeStandard()) {
5542 if (mCurAppTimeTracker != r.appTimeTracker) {
5543 // We are switching app tracking. Complete the current one.
5544 if (mCurAppTimeTracker != null) {
5545 mCurAppTimeTracker.stop();
5546 mH.obtainMessage(
5547 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005548 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 mCurAppTimeTracker = null;
5550 }
5551 if (r.appTimeTracker != null) {
5552 mCurAppTimeTracker = r.appTimeTracker;
5553 startTimeTrackingFocusedActivityLocked();
5554 }
5555 } else {
5556 startTimeTrackingFocusedActivityLocked();
5557 }
5558 } else {
5559 r.appTimeTracker = null;
5560 }
5561 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5562 // TODO: Probably not, because we don't want to resume voice on switching
5563 // back to this activity
5564 if (task.voiceInteractor != null) {
5565 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5566 } else {
5567 finishRunningVoiceLocked();
5568
5569 if (mLastResumedActivity != null) {
5570 final IVoiceInteractionSession session;
5571
Louis Changcdec0802019-11-11 11:45:07 +08005572 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005573 if (lastResumedActivityTask != null
5574 && lastResumedActivityTask.voiceSession != null) {
5575 session = lastResumedActivityTask.voiceSession;
5576 } else {
5577 session = mLastResumedActivity.voiceSession;
5578 }
5579
5580 if (session != null) {
5581 // We had been in a voice interaction session, but now focused has
5582 // move to something different. Just finish the session, we can't
5583 // return to it and retain the proper state and synchronization with
5584 // the voice interaction service.
5585 finishVoiceTask(session);
5586 }
5587 }
5588 }
5589
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005590 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5591 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005592 }
5593 updateResumedAppTrace(r);
5594 mLastResumedActivity = r;
5595
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005596 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597
5598 applyUpdateLockStateLocked(r);
5599 applyUpdateVrModeLocked(r);
5600
Jeff Changd136e772019-11-05 20:33:52 +08005601 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005602 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 r == null ? "NULL" : r.shortComponentName,
5604 reason);
5605 }
5606
5607 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5608 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005609 final ActivityTaskManagerInternal.SleepToken token =
5610 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005611 updateSleepIfNeededLocked();
5612 return token;
5613 }
5614 }
5615
5616 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005617 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005618 final boolean wasSleeping = mSleeping;
5619 boolean updateOomAdj = false;
5620
5621 if (!shouldSleep) {
5622 // If wasSleeping is true, we need to wake up activity manager state from when
5623 // we started sleeping. In either case, we need to apply the sleep tokens, which
5624 // will wake up stacks or put them to sleep as appropriate.
5625 if (wasSleeping) {
5626 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005627 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5628 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005629 startTimeTrackingFocusedActivityLocked();
5630 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005631 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005632 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5633 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005634 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005635 if (wasSleeping) {
5636 updateOomAdj = true;
5637 }
5638 } else if (!mSleeping && shouldSleep) {
5639 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005640 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5641 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005642 if (mCurAppTimeTracker != null) {
5643 mCurAppTimeTracker.stop();
5644 }
5645 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005646 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005647 mStackSupervisor.goingToSleepLocked();
5648 updateResumedAppTrace(null /* resumed */);
5649 updateOomAdj = true;
5650 }
5651 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005652 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005653 }
5654 }
5655
5656 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005657 mH.removeCallbacks(mUpdateOomAdjRunnable);
5658 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005659 }
5660
Wale Ogunwale53783742018-09-16 10:21:51 -07005661 void updateCpuStats() {
5662 mH.post(mAmInternal::updateCpuStats);
5663 }
5664
Hui Yu03d12402018-12-06 18:00:37 -08005665 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5666 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005667 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5668 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005669 mH.sendMessage(m);
5670 }
5671
Hui Yu03d12402018-12-06 18:00:37 -08005672 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005673 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005674 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005675 if (task != null) {
5676 final ActivityRecord rootActivity = task.getRootActivity();
5677 if (rootActivity != null) {
5678 taskRoot = rootActivity.mActivityComponent;
5679 }
5680 }
5681
Hui Yu03d12402018-12-06 18:00:37 -08005682 final Message m = PooledLambda.obtainMessage(
5683 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005684 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005685 mH.sendMessage(m);
5686 }
5687
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005688 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5689 String hostingType) {
5690 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005691 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5692 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005693 + activity.processName);
5694 }
5695 // Post message to start process to avoid possible deadlock of calling into AMS with the
5696 // ATMS lock held.
5697 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5698 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5699 isTop, hostingType, activity.intent.getComponent());
5700 mH.sendMessage(m);
5701 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005702 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005703 }
5704 }
5705
Wale Ogunwale53783742018-09-16 10:21:51 -07005706 void setBooting(boolean booting) {
5707 mAmInternal.setBooting(booting);
5708 }
5709
5710 boolean isBooting() {
5711 return mAmInternal.isBooting();
5712 }
5713
5714 void setBooted(boolean booted) {
5715 mAmInternal.setBooted(booted);
5716 }
5717
5718 boolean isBooted() {
5719 return mAmInternal.isBooted();
5720 }
5721
5722 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5723 mH.post(() -> {
5724 if (finishBooting) {
5725 mAmInternal.finishBooting();
5726 }
5727 if (enableScreen) {
5728 mInternal.enableScreenAfterBoot(isBooted());
5729 }
5730 });
5731 }
5732
5733 void setHeavyWeightProcess(ActivityRecord root) {
5734 mHeavyWeightProcess = root.app;
5735 final Message m = PooledLambda.obtainMessage(
5736 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005737 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005738 mH.sendMessage(m);
5739 }
5740
5741 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5742 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5743 return;
5744 }
5745
5746 mHeavyWeightProcess = null;
5747 final Message m = PooledLambda.obtainMessage(
5748 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5749 proc.mUserId);
5750 mH.sendMessage(m);
5751 }
5752
5753 private void cancelHeavyWeightProcessNotification(int userId) {
5754 final INotificationManager inm = NotificationManager.getService();
5755 if (inm == null) {
5756 return;
5757 }
5758 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005759 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005760 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5761 } catch (RuntimeException e) {
5762 Slog.w(TAG, "Error canceling notification for service", e);
5763 } catch (RemoteException e) {
5764 }
5765
5766 }
5767
5768 private void postHeavyWeightProcessNotification(
5769 WindowProcessController proc, Intent intent, int userId) {
5770 if (proc == null) {
5771 return;
5772 }
5773
5774 final INotificationManager inm = NotificationManager.getService();
5775 if (inm == null) {
5776 return;
5777 }
5778
5779 try {
5780 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5781 String text = mContext.getString(R.string.heavy_weight_notification,
5782 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5783 Notification notification =
5784 new Notification.Builder(context,
5785 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5786 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5787 .setWhen(0)
5788 .setOngoing(true)
5789 .setTicker(text)
5790 .setColor(mContext.getColor(
5791 com.android.internal.R.color.system_notification_accent_color))
5792 .setContentTitle(text)
5793 .setContentText(
5794 mContext.getText(R.string.heavy_weight_notification_detail))
5795 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5796 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5797 new UserHandle(userId)))
5798 .build();
5799 try {
5800 inm.enqueueNotificationWithTag("android", "android", null,
5801 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5802 } catch (RuntimeException e) {
5803 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5804 } catch (RemoteException e) {
5805 }
5806 } catch (PackageManager.NameNotFoundException e) {
5807 Slog.w(TAG, "Unable to create context for heavy notification", e);
5808 }
5809
5810 }
5811
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005812 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5813 IBinder token, String resultWho, int requestCode, Intent[] intents,
5814 String[] resolvedTypes, int flags, Bundle bOptions) {
5815
5816 ActivityRecord activity = null;
5817 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5818 activity = ActivityRecord.isInStackLocked(token);
5819 if (activity == null) {
5820 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5821 return null;
5822 }
5823 if (activity.finishing) {
5824 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5825 return null;
5826 }
5827 }
5828
5829 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5830 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5831 bOptions);
5832 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5833 if (noCreate) {
5834 return rec;
5835 }
5836 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5837 if (activity.pendingResults == null) {
5838 activity.pendingResults = new HashSet<>();
5839 }
5840 activity.pendingResults.add(rec.ref);
5841 }
5842 return rec;
5843 }
5844
Andrii Kulian52d255c2018-07-13 11:32:19 -07005845 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005846 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005847 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005848 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5849 mCurAppTimeTracker.start(resumedActivity.packageName);
5850 }
5851 }
5852
5853 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5854 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005855 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005856 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5857 }
5858 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005859 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005860 constructResumedTraceName(resumed.packageName), 0);
5861 }
5862 mTracedResumedActivity = resumed;
5863 }
5864
5865 private String constructResumedTraceName(String packageName) {
5866 return "focused app: " + packageName;
5867 }
5868
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005869 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005870 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005871 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005872 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005873 // mainStack is null during startup.
5874 if (mainStack != null) {
5875 if (changes != 0 && starting == null) {
5876 // If the configuration changed, and the caller is not already
5877 // in the process of starting an activity, then find the top
5878 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005879 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005880 }
5881
5882 if (starting != null) {
5883 kept = starting.ensureActivityConfiguration(changes,
5884 false /* preserveWindow */);
5885 // And we need to make sure at this point that all other activities
5886 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005887 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005888 !PRESERVE_WINDOWS);
5889 }
5890 }
5891
5892 return kept;
5893 }
5894
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005895 void scheduleAppGcsLocked() {
5896 mH.post(() -> mAmInternal.scheduleAppGcs());
5897 }
5898
Wale Ogunwale53783742018-09-16 10:21:51 -07005899 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5900 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5901 }
5902
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005903 /**
5904 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5905 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5906 * on demand.
5907 */
5908 IPackageManager getPackageManager() {
5909 return AppGlobals.getPackageManager();
5910 }
5911
5912 PackageManagerInternal getPackageManagerInternalLocked() {
5913 if (mPmInternal == null) {
5914 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5915 }
5916 return mPmInternal;
5917 }
5918
Hai Zhangf4da9be2019-05-01 13:46:06 +08005919 PermissionPolicyInternal getPermissionPolicyInternal() {
5920 if (mPermissionPolicyInternal == null) {
5921 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5922 }
5923 return mPermissionPolicyInternal;
5924 }
5925
Wale Ogunwale008163e2018-07-23 23:11:08 -07005926 AppWarnings getAppWarningsLocked() {
5927 return mAppWarnings;
5928 }
5929
Wale Ogunwale214f3482018-10-04 11:00:47 -07005930 Intent getHomeIntent() {
5931 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5932 intent.setComponent(mTopComponent);
5933 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5934 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5935 intent.addCategory(Intent.CATEGORY_HOME);
5936 }
5937 return intent;
5938 }
5939
Chilun2ef71f72018-11-16 17:57:15 +08005940 /**
5941 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5942 * activities.
5943 *
5944 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5945 * component defined in config_secondaryHomeComponent.
5946 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5947 */
5948 Intent getSecondaryHomeIntent(String preferredPackage) {
5949 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005950 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5951 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5952 if (preferredPackage == null || useSystemProvidedLauncher) {
5953 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005954 final String secondaryHomeComponent = mContext.getResources().getString(
5955 com.android.internal.R.string.config_secondaryHomeComponent);
5956 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5957 } else {
5958 intent.setPackage(preferredPackage);
5959 }
5960 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5961 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5962 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5963 }
5964 return intent;
5965 }
5966
Wale Ogunwale214f3482018-10-04 11:00:47 -07005967 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5968 if (info == null) return null;
5969 ApplicationInfo newInfo = new ApplicationInfo(info);
5970 newInfo.initForUser(userId);
5971 return newInfo;
5972 }
5973
Wale Ogunwale9c103022018-10-18 07:44:54 -07005974 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005975 if (uid == SYSTEM_UID) {
5976 // The system gets to run in any process. If there are multiple processes with the same
5977 // uid, just pick the first (this should never happen).
5978 final SparseArray<WindowProcessController> procs =
5979 mProcessNames.getMap().get(processName);
5980 if (procs == null) return null;
5981 final int procCount = procs.size();
5982 for (int i = 0; i < procCount; i++) {
5983 final int procUid = procs.keyAt(i);
5984 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5985 // Don't use an app process or different user process for system component.
5986 continue;
5987 }
5988 return procs.valueAt(i);
5989 }
5990 }
5991
5992 return mProcessNames.get(processName, uid);
5993 }
5994
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005995 WindowProcessController getProcessController(IApplicationThread thread) {
5996 if (thread == null) {
5997 return null;
5998 }
5999
6000 final IBinder threadBinder = thread.asBinder();
6001 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6002 for (int i = pmap.size()-1; i >= 0; i--) {
6003 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6004 for (int j = procs.size() - 1; j >= 0; j--) {
6005 final WindowProcessController proc = procs.valueAt(j);
6006 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6007 return proc;
6008 }
6009 }
6010 }
6011
6012 return null;
6013 }
6014
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006015 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006016 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006017 if (proc == null) return null;
6018 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6019 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006020 }
6021 return null;
6022 }
6023
Riddle Hsua0536432019-02-16 00:38:59 +08006024 int getUidState(int uid) {
6025 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006026 }
6027
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006028 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006029 // A uid is considered to be foreground if it has a visible non-toast window.
6030 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006031 }
6032
Ricky Wai96f5c352019-04-10 18:40:17 +01006033 boolean isDeviceOwner(int uid) {
6034 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006035 }
6036
Ricky Wai96f5c352019-04-10 18:40:17 +01006037 void setDeviceOwnerUid(int uid) {
6038 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006039 }
6040
Wale Ogunwale9de19442018-10-18 19:05:03 -07006041 /**
6042 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6043 * the whitelist
6044 */
6045 String getPendingTempWhitelistTagForUidLocked(int uid) {
6046 return mPendingTempWhitelist.get(uid);
6047 }
6048
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006049 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6050 if (true || Build.IS_USER) {
6051 return;
6052 }
6053
6054 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6055 StrictMode.allowThreadDiskWrites();
6056 try {
6057 File tracesDir = new File("/data/anr");
6058 File tracesFile = null;
6059 try {
6060 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6061
6062 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006063 String timeString =
6064 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6065 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006066 sb.append(": ");
6067 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6068 sb.append(" since ");
6069 sb.append(msg);
6070 FileOutputStream fos = new FileOutputStream(tracesFile);
6071 fos.write(sb.toString().getBytes());
6072 if (app == null) {
6073 fos.write("\n*** No application process!".getBytes());
6074 }
6075 fos.close();
6076 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6077 } catch (IOException e) {
6078 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6079 return;
6080 }
6081
6082 if (app != null && app.getPid() > 0) {
6083 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6084 firstPids.add(app.getPid());
6085 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6086 }
6087
6088 File lastTracesFile = null;
6089 File curTracesFile = null;
6090 for (int i=9; i>=0; i--) {
6091 String name = String.format(Locale.US, "slow%02d.txt", i);
6092 curTracesFile = new File(tracesDir, name);
6093 if (curTracesFile.exists()) {
6094 if (lastTracesFile != null) {
6095 curTracesFile.renameTo(lastTracesFile);
6096 } else {
6097 curTracesFile.delete();
6098 }
6099 }
6100 lastTracesFile = curTracesFile;
6101 }
6102 tracesFile.renameTo(curTracesFile);
6103 } finally {
6104 StrictMode.setThreadPolicy(oldPolicy);
6105 }
6106 }
6107
Michal Karpinskida34cd42019-04-02 19:46:52 +01006108 boolean isAssociatedCompanionApp(int userId, int uid) {
6109 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6110 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006111 return false;
6112 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006113 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006114 }
6115
Issei Suzuki734bc942019-06-05 13:59:52 +02006116 void notifySingleTaskDisplayEmpty(int displayId) {
6117 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6118 }
6119
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006120 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006121 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006122
6123
Wale Ogunwale98875612018-10-12 07:53:02 -07006124 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6125 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006126
Riddle Hsud93a6c42018-11-29 21:50:06 +08006127 H(Looper looper) {
6128 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006129 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006130
6131 @Override
6132 public void handleMessage(Message msg) {
6133 switch (msg.what) {
6134 case REPORT_TIME_TRACKER_MSG: {
6135 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6136 tracker.deliverResult(mContext);
6137 } break;
6138 }
6139 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006140 }
6141
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006142 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006143 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006144
6145 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006146 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006147 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006148
6149 @Override
6150 public void handleMessage(Message msg) {
6151 switch (msg.what) {
6152 case DISMISS_DIALOG_UI_MSG: {
6153 final Dialog d = (Dialog) msg.obj;
6154 d.dismiss();
6155 break;
6156 }
6157 }
6158 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006159 }
6160
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 final class LocalService extends ActivityTaskManagerInternal {
6162 @Override
6163 public SleepToken acquireSleepToken(String tag, int displayId) {
6164 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006165 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167
6168 @Override
6169 public ComponentName getHomeActivityForUser(int userId) {
6170 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006171 final ActivityRecord homeActivity =
6172 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006173 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175 }
6176
6177 @Override
6178 public void onLocalVoiceInteractionStarted(IBinder activity,
6179 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6180 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006181 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 }
6183 }
6184
6185 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006186 public void notifySingleTaskDisplayDrawn(int displayId) {
6187 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6188 }
6189
6190 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006191 public void notifyAppTransitionFinished() {
6192 synchronized (mGlobalLock) {
6193 mStackSupervisor.notifyAppTransitionDone();
6194 }
6195 }
6196
6197 @Override
6198 public void notifyAppTransitionCancelled() {
6199 synchronized (mGlobalLock) {
6200 mStackSupervisor.notifyAppTransitionDone();
6201 }
6202 }
6203
6204 @Override
6205 public List<IBinder> getTopVisibleActivities() {
6206 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006207 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 }
6209 }
6210
6211 @Override
6212 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6213 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006214 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006215 }
6216 }
6217
6218 @Override
6219 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6220 Bundle bOptions) {
6221 Preconditions.checkNotNull(intents, "intents");
6222 final String[] resolvedTypes = new String[intents.length];
6223
6224 // UID of the package on user userId.
6225 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6226 // packageUid may not be initialized.
6227 int packageUid = 0;
6228 final long ident = Binder.clearCallingIdentity();
6229
6230 try {
6231 for (int i = 0; i < intents.length; i++) {
6232 resolvedTypes[i] =
6233 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6234 }
6235
6236 packageUid = AppGlobals.getPackageManager().getPackageUid(
6237 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6238 } catch (RemoteException e) {
6239 // Shouldn't happen.
6240 } finally {
6241 Binder.restoreCallingIdentity(ident);
6242 }
6243
Riddle Hsu591bf612019-02-14 17:55:31 +08006244 return getActivityStartController().startActivitiesInPackage(
6245 packageUid, packageName,
6246 intents, resolvedTypes, null /* resultTo */,
6247 SafeActivityOptions.fromBundle(bOptions), userId,
6248 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6249 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006250 }
6251
6252 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006253 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6254 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6255 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6256 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006257 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006258 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006259 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6260 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6261 userId, validateIncomingUser, originatingPendingIntent,
6262 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006263 }
6264 }
6265
6266 @Override
6267 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6268 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6269 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006270 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006271 PendingIntentRecord originatingPendingIntent,
6272 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006273 synchronized (mGlobalLock) {
6274 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6275 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6276 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006277 validateIncomingUser, originatingPendingIntent,
6278 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006279 }
6280 }
6281
6282 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006283 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6284 Intent intent, Bundle options, int userId) {
6285 return ActivityTaskManagerService.this.startActivityAsUser(
6286 caller, callerPacakge, intent,
6287 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6288 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6289 false /*validateIncomingUser*/);
6290 }
6291
6292 @Override
lumark588a3e82018-07-20 18:53:54 +08006293 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006294 synchronized (mGlobalLock) {
6295
6296 // We might change the visibilities here, so prepare an empty app transition which
6297 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006298 final DisplayContent displayContent =
6299 mRootActivityContainer.getDisplayContent(displayId);
6300 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006301 return;
6302 }
Louis Chang677921f2019-12-06 16:44:24 +08006303 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006304 final boolean wasTransitionSet =
6305 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006307 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006308 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006309 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310
6311 // If there was a transition set already we don't want to interfere with it as we
6312 // might be starting it too early.
6313 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006314 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006315 }
6316 }
6317 if (callback != null) {
6318 callback.run();
6319 }
6320 }
6321
6322 @Override
6323 public void notifyKeyguardTrustedChanged() {
6324 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006325 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006326 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006327 }
6328 }
6329 }
6330
6331 /**
6332 * Called after virtual display Id is updated by
6333 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6334 * {@param vrVr2dDisplayId}.
6335 */
6336 @Override
6337 public void setVr2dDisplayId(int vr2dDisplayId) {
6338 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6339 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006340 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006341 }
6342 }
6343
6344 @Override
6345 public void setFocusedActivity(IBinder token) {
6346 synchronized (mGlobalLock) {
6347 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6348 if (r == null) {
6349 throw new IllegalArgumentException(
6350 "setFocusedActivity: No activity record matching token=" + token);
6351 }
Louis Chang19443452018-10-09 12:10:21 +08006352 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006353 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006354 }
6355 }
6356 }
6357
6358 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006359 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006360 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006361 }
6362
6363 @Override
6364 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006365 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006366 }
6367
6368 @Override
6369 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006370 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006371 }
6372
6373 @Override
6374 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6375 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6376 }
6377
6378 @Override
6379 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006380 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006381 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006382
6383 @Override
6384 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6385 synchronized (mGlobalLock) {
6386 mActiveVoiceInteractionServiceComponent = component;
6387 }
6388 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006389
6390 @Override
6391 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6392 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6393 return;
6394 }
6395 synchronized (mGlobalLock) {
6396 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6397 if (types == null) {
6398 if (uid < 0) {
6399 return;
6400 }
6401 types = new ArrayMap<>();
6402 mAllowAppSwitchUids.put(userId, types);
6403 }
6404 if (uid < 0) {
6405 types.remove(type);
6406 } else {
6407 types.put(type, uid);
6408 }
6409 }
6410 }
6411
6412 @Override
6413 public void onUserStopped(int userId) {
6414 synchronized (mGlobalLock) {
6415 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6416 mAllowAppSwitchUids.remove(userId);
6417 }
6418 }
6419
6420 @Override
6421 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6422 synchronized (mGlobalLock) {
6423 return ActivityTaskManagerService.this.isGetTasksAllowed(
6424 caller, callingPid, callingUid);
6425 }
6426 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006427
Riddle Hsua0536432019-02-16 00:38:59 +08006428 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006429 @Override
6430 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006431 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006432 mProcessNames.put(proc.mName, proc.mUid, proc);
6433 }
6434 }
6435
Riddle Hsua0536432019-02-16 00:38:59 +08006436 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006437 @Override
6438 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006439 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006440 mProcessNames.remove(name, uid);
6441 }
6442 }
6443
Riddle Hsua0536432019-02-16 00:38:59 +08006444 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006445 @Override
6446 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006447 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006448 if (proc == mHomeProcess) {
6449 mHomeProcess = null;
6450 }
6451 if (proc == mPreviousProcess) {
6452 mPreviousProcess = null;
6453 }
6454 }
6455 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006456
Riddle Hsua0536432019-02-16 00:38:59 +08006457 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006458 @Override
6459 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006460 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006461 return mTopProcessState;
6462 }
6463 }
6464
Riddle Hsua0536432019-02-16 00:38:59 +08006465 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006466 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006467 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006468 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006469 return proc == mHeavyWeightProcess;
6470 }
6471 }
6472
Riddle Hsua0536432019-02-16 00:38:59 +08006473 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006474 @Override
6475 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006476 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006477 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6478 }
6479 }
6480
6481 @Override
6482 public void finishHeavyWeightApp() {
6483 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006484 if (mHeavyWeightProcess != null) {
6485 mHeavyWeightProcess.finishActivities();
6486 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006487 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6488 mHeavyWeightProcess);
6489 }
6490 }
6491
Riddle Hsua0536432019-02-16 00:38:59 +08006492 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006493 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006494 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006495 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006496 return isSleepingLocked();
6497 }
6498 }
6499
6500 @Override
6501 public boolean isShuttingDown() {
6502 synchronized (mGlobalLock) {
6503 return mShuttingDown;
6504 }
6505 }
6506
6507 @Override
6508 public boolean shuttingDown(boolean booted, int timeout) {
6509 synchronized (mGlobalLock) {
6510 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006511 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006512 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006513 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006514 return mStackSupervisor.shutdownLocked(timeout);
6515 }
6516 }
6517
6518 @Override
6519 public void enableScreenAfterBoot(boolean booted) {
6520 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006521 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006522 mWindowManager.enableScreenAfterBoot();
6523 updateEventDispatchingLocked(booted);
6524 }
6525 }
6526
6527 @Override
6528 public boolean showStrictModeViolationDialog() {
6529 synchronized (mGlobalLock) {
6530 return mShowDialogs && !mSleeping && !mShuttingDown;
6531 }
6532 }
6533
6534 @Override
6535 public void showSystemReadyErrorDialogsIfNeeded() {
6536 synchronized (mGlobalLock) {
6537 try {
6538 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6539 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6540 + " data partition or your device will be unstable.");
6541 mUiHandler.post(() -> {
6542 if (mShowDialogs) {
6543 AlertDialog d = new BaseErrorDialog(mUiContext);
6544 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6545 d.setCancelable(false);
6546 d.setTitle(mUiContext.getText(R.string.android_system_label));
6547 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6548 d.setButton(DialogInterface.BUTTON_POSITIVE,
6549 mUiContext.getText(R.string.ok),
6550 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6551 d.show();
6552 }
6553 });
6554 }
6555 } catch (RemoteException e) {
6556 }
6557
6558 if (!Build.isBuildConsistent()) {
6559 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6560 mUiHandler.post(() -> {
6561 if (mShowDialogs) {
6562 AlertDialog d = new BaseErrorDialog(mUiContext);
6563 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6564 d.setCancelable(false);
6565 d.setTitle(mUiContext.getText(R.string.android_system_label));
6566 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6567 d.setButton(DialogInterface.BUTTON_POSITIVE,
6568 mUiContext.getText(R.string.ok),
6569 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6570 d.show();
6571 }
6572 });
6573 }
6574 }
6575 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006576
6577 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006578 public void onProcessMapped(int pid, WindowProcessController proc) {
6579 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006580 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006581 }
6582 }
6583
6584 @Override
6585 public void onProcessUnMapped(int pid) {
6586 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006587 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006588 }
6589 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006590
6591 @Override
6592 public void onPackageDataCleared(String name) {
6593 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006594 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006595 mAppWarnings.onPackageDataCleared(name);
6596 }
6597 }
6598
6599 @Override
6600 public void onPackageUninstalled(String name) {
6601 synchronized (mGlobalLock) {
6602 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006603 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006604 }
6605 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006606
6607 @Override
6608 public void onPackageAdded(String name, boolean replacing) {
6609 synchronized (mGlobalLock) {
6610 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6611 }
6612 }
6613
6614 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006615 public void onPackageReplaced(ApplicationInfo aInfo) {
6616 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006617 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006618 }
6619 }
6620
6621 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006622 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6623 synchronized (mGlobalLock) {
6624 return compatibilityInfoForPackageLocked(ai);
6625 }
6626 }
6627
Yunfan Chen75157d72018-07-27 14:47:21 +09006628 /**
6629 * Set the corresponding display information for the process global configuration. To be
6630 * called when we need to show IME on a different display.
6631 *
6632 * @param pid The process id associated with the IME window.
6633 * @param displayId The ID of the display showing the IME.
6634 */
6635 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006636 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006637 // Don't update process-level configuration for Multi-Client IME process since other
6638 // IMEs on other displays will also receive this configuration change due to IME
6639 // services use the same application config/context.
6640 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006641
Yunfan Chen75157d72018-07-27 14:47:21 +09006642 if (pid == MY_PID || pid < 0) {
6643 if (DEBUG_CONFIGURATION) {
6644 Slog.w(TAG,
6645 "Trying to update display configuration for system/invalid process.");
6646 }
6647 return;
6648 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006649 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006650 final DisplayContent displayContent =
6651 mRootActivityContainer.getDisplayContent(displayId);
6652 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006653 // Call might come when display is not yet added or has been removed.
6654 if (DEBUG_CONFIGURATION) {
6655 Slog.w(TAG, "Trying to update display configuration for non-existing "
6656 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006657 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006658 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006659 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006660 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006661 if (process == null) {
6662 if (DEBUG_CONFIGURATION) {
6663 Slog.w(TAG, "Trying to update display configuration for invalid "
6664 + "process, pid=" + pid);
6665 }
6666 return;
6667 }
lumarkddc77fb2019-06-27 22:22:23 +08006668 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006669 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006670 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006671 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006672
6673 @Override
6674 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006675 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006676 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006677 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6678 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006679 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006680 }
6681 }
6682 }
6683
6684 @Override
6685 public void clearPendingResultForActivity(IBinder activityToken,
6686 WeakReference<PendingIntentRecord> pir) {
6687 synchronized (mGlobalLock) {
6688 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6689 if (r != null && r.pendingResults != null) {
6690 r.pendingResults.remove(pir);
6691 }
6692 }
6693 }
6694
6695 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006696 public ActivityTokens getTopActivityForTask(int taskId) {
6697 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006698 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6699 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006700 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6701 + " Requested task not found");
6702 return null;
6703 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006704 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006705 if (activity == null) {
6706 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6707 + " Requested activity not found");
6708 return null;
6709 }
6710 if (!activity.attachedToProcess()) {
6711 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6712 + activity);
6713 return null;
6714 }
6715 return new ActivityTokens(activity.appToken, activity.assistToken,
6716 activity.app.getThread());
6717 }
6718 }
6719
6720 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006721 public IIntentSender getIntentSender(int type, String packageName,
6722 int callingUid, int userId, IBinder token, String resultWho,
6723 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6724 Bundle bOptions) {
6725 synchronized (mGlobalLock) {
6726 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6727 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6728 }
6729 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006730
6731 @Override
6732 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6733 synchronized (mGlobalLock) {
6734 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6735 if (r == null) {
6736 return null;
6737 }
6738 if (r.mServiceConnectionsHolder == null) {
6739 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6740 ActivityTaskManagerService.this, r);
6741 }
6742
6743 return r.mServiceConnectionsHolder;
6744 }
6745 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006746
6747 @Override
6748 public Intent getHomeIntent() {
6749 synchronized (mGlobalLock) {
6750 return ActivityTaskManagerService.this.getHomeIntent();
6751 }
6752 }
6753
6754 @Override
6755 public boolean startHomeActivity(int userId, String reason) {
6756 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006757 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006758 }
6759 }
6760
6761 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006762 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006763 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006764 synchronized (mGlobalLock) {
6765 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006766 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006767 }
Chilun8b1f1be2019-03-13 17:14:36 +08006768 }
6769
6770 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006771 public boolean startHomeOnAllDisplays(int userId, String reason) {
6772 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006773 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006774 }
6775 }
6776
Riddle Hsua0536432019-02-16 00:38:59 +08006777 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006778 @Override
6779 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006780 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006781 if (mFactoryTest == FACTORY_TEST_OFF) {
6782 return false;
6783 }
6784 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6785 && wpc.mName.equals(mTopComponent.getPackageName())) {
6786 return true;
6787 }
6788 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6789 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6790 }
6791 }
6792
6793 @Override
6794 public void updateTopComponentForFactoryTest() {
6795 synchronized (mGlobalLock) {
6796 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6797 return;
6798 }
6799 final ResolveInfo ri = mContext.getPackageManager()
6800 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6801 final CharSequence errorMsg;
6802 if (ri != null) {
6803 final ActivityInfo ai = ri.activityInfo;
6804 final ApplicationInfo app = ai.applicationInfo;
6805 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6806 mTopAction = Intent.ACTION_FACTORY_TEST;
6807 mTopData = null;
6808 mTopComponent = new ComponentName(app.packageName, ai.name);
6809 errorMsg = null;
6810 } else {
6811 errorMsg = mContext.getResources().getText(
6812 com.android.internal.R.string.factorytest_not_system);
6813 }
6814 } else {
6815 errorMsg = mContext.getResources().getText(
6816 com.android.internal.R.string.factorytest_no_action);
6817 }
6818 if (errorMsg == null) {
6819 return;
6820 }
6821
6822 mTopAction = null;
6823 mTopData = null;
6824 mTopComponent = null;
6825 mUiHandler.post(() -> {
6826 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6827 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006828 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006829 });
6830 }
6831 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832
Riddle Hsua0536432019-02-16 00:38:59 +08006833 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006834 @Override
6835 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6836 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006837 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006839 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840
6841 wpc.clearRecentTasks();
6842 wpc.clearActivities();
6843
6844 if (wpc.isInstrumenting()) {
6845 finishInstrumentationCallback.run();
6846 }
6847
Jorim Jaggid0752812018-10-16 16:07:20 +02006848 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006849 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006850 try {
6851 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6852 // If there was nothing to resume, and we are not already restarting
6853 // this process, but there is a visible activity that is hosted by the
6854 // process...then make sure all visible activities are running, taking
6855 // care of restarting this process.
6856 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6857 !PRESERVE_WINDOWS);
6858 }
6859 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006860 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 }
6863 }
6864 }
6865
6866 @Override
6867 public void closeSystemDialogs(String reason) {
6868 enforceNotIsolatedCaller("closeSystemDialogs");
6869
6870 final int pid = Binder.getCallingPid();
6871 final int uid = Binder.getCallingUid();
6872 final long origId = Binder.clearCallingIdentity();
6873 try {
6874 synchronized (mGlobalLock) {
6875 // Only allow this from foreground processes, so that background
6876 // applications can't abuse it to prevent system UI from being shown.
6877 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006878 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 if (!proc.isPerceptible()) {
6880 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6881 + " from background process " + proc);
6882 return;
6883 }
6884 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006885 mWindowManager.closeSystemDialogs(reason);
6886
Wale Ogunwaled32da472018-11-16 07:19:28 -08006887 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006889 // Call into AM outside the synchronized block.
6890 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006891 } finally {
6892 Binder.restoreCallingIdentity(origId);
6893 }
6894 }
6895
6896 @Override
6897 public void cleanupDisabledPackageComponents(
6898 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6899 synchronized (mGlobalLock) {
6900 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006901 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006903 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 mStackSupervisor.scheduleIdleLocked();
6905 }
6906
6907 // Clean-up disabled tasks
6908 getRecentTasks().cleanupDisabledPackageTasksLocked(
6909 packageName, disabledClasses, userId);
6910 }
6911 }
6912
6913 @Override
6914 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6915 int userId) {
6916 synchronized (mGlobalLock) {
6917
6918 boolean didSomething =
6919 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006920 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006921 null, doit, evenPersistent, userId);
6922 return didSomething;
6923 }
6924 }
6925
6926 @Override
6927 public void resumeTopActivities(boolean scheduleIdle) {
6928 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006929 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006930 if (scheduleIdle) {
6931 mStackSupervisor.scheduleIdleLocked();
6932 }
6933 }
6934 }
6935
Riddle Hsua0536432019-02-16 00:38:59 +08006936 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006937 @Override
6938 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006939 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6941 }
6942 }
6943
Riddle Hsua0536432019-02-16 00:38:59 +08006944 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006945 @Override
6946 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006947 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006948 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6949 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6950 }
6951 try {
6952 return mRootActivityContainer.attachApplication(wpc);
6953 } finally {
6954 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6955 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 }
6957 }
6958
6959 @Override
6960 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6961 try {
6962 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6963 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6964 }
6965 } catch (RemoteException ex) {
6966 throw new SecurityException("Fail to check is caller a privileged app", ex);
6967 }
6968
6969 synchronized (mGlobalLock) {
6970 final long ident = Binder.clearCallingIdentity();
6971 try {
6972 if (mAmInternal.shouldConfirmCredentials(userId)) {
6973 if (mKeyguardController.isKeyguardLocked()) {
6974 // Showing launcher to avoid user entering credential twice.
6975 startHomeActivity(currentUserId, "notifyLockedProfile");
6976 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006977 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 }
6979 } finally {
6980 Binder.restoreCallingIdentity(ident);
6981 }
6982 }
6983 }
6984
6985 @Override
6986 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6987 mAmInternal.enforceCallingPermission(
6988 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6989
6990 synchronized (mGlobalLock) {
6991 final long ident = Binder.clearCallingIdentity();
6992 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006993 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6994 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006996 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6997 UserHandle.CURRENT);
6998 } finally {
6999 Binder.restoreCallingIdentity(ident);
7000 }
7001 }
7002 }
7003
7004 @Override
7005 public void writeActivitiesToProto(ProtoOutputStream proto) {
7006 synchronized (mGlobalLock) {
7007 // The output proto of "activity --proto activities"
7008 // is ActivityManagerServiceDumpActivitiesProto
Jeffrey Huangcb782852019-12-05 11:28:11 -08007009 mRootActivityContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007010 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7011 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007012 }
7013 }
7014
7015 @Override
7016 public void saveANRState(String reason) {
7017 synchronized (mGlobalLock) {
7018 final StringWriter sw = new StringWriter();
7019 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7020 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7021 if (reason != null) {
7022 pw.println(" Reason: " + reason);
7023 }
7024 pw.println();
7025 getActivityStartController().dump(pw, " ", null);
7026 pw.println();
7027 pw.println("-------------------------------------------------------------------------------");
7028 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7029 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7030 "" /* header */);
7031 pw.println();
7032 pw.close();
7033
7034 mLastANRState = sw.toString();
7035 }
7036 }
7037
7038 @Override
7039 public void clearSavedANRState() {
7040 synchronized (mGlobalLock) {
7041 mLastANRState = null;
7042 }
7043 }
7044
7045 @Override
7046 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7047 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7048 synchronized (mGlobalLock) {
7049 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7050 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7051 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7052 dumpLastANRLocked(pw);
7053 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7054 dumpLastANRTracesLocked(pw);
7055 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7056 dumpActivityStarterLocked(pw, dumpPackage);
7057 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7058 dumpActivityContainersLocked(pw);
7059 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7060 if (getRecentTasks() != null) {
7061 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7062 }
7063 }
7064 }
7065 }
7066
7067 @Override
7068 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7069 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7070 int wakefulness) {
7071 synchronized (mGlobalLock) {
7072 if (mHomeProcess != null && (dumpPackage == null
7073 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7074 if (needSep) {
7075 pw.println();
7076 needSep = false;
7077 }
7078 pw.println(" mHomeProcess: " + mHomeProcess);
7079 }
7080 if (mPreviousProcess != null && (dumpPackage == null
7081 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7082 if (needSep) {
7083 pw.println();
7084 needSep = false;
7085 }
7086 pw.println(" mPreviousProcess: " + mPreviousProcess);
7087 }
7088 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7089 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7090 StringBuilder sb = new StringBuilder(128);
7091 sb.append(" mPreviousProcessVisibleTime: ");
7092 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7093 pw.println(sb);
7094 }
7095 if (mHeavyWeightProcess != null && (dumpPackage == null
7096 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7097 if (needSep) {
7098 pw.println();
7099 needSep = false;
7100 }
7101 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7102 }
7103 if (dumpPackage == null) {
7104 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007105 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 }
7107 if (dumpAll) {
7108 if (dumpPackage == null) {
7109 pw.println(" mConfigWillChange: "
7110 + getTopDisplayFocusedStack().mConfigWillChange);
7111 }
7112 if (mCompatModePackages.getPackages().size() > 0) {
7113 boolean printed = false;
7114 for (Map.Entry<String, Integer> entry
7115 : mCompatModePackages.getPackages().entrySet()) {
7116 String pkg = entry.getKey();
7117 int mode = entry.getValue();
7118 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7119 continue;
7120 }
7121 if (!printed) {
7122 pw.println(" mScreenCompatPackages:");
7123 printed = true;
7124 }
7125 pw.println(" " + pkg + ": " + mode);
7126 }
7127 }
7128 }
7129
7130 if (dumpPackage == null) {
7131 pw.println(" mWakefulness="
7132 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007133 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 if (mRunningVoice != null) {
7135 pw.println(" mRunningVoice=" + mRunningVoice);
7136 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7137 }
7138 pw.println(" mSleeping=" + mSleeping);
7139 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7140 pw.println(" mVrController=" + mVrController);
7141 }
7142 if (mCurAppTimeTracker != null) {
7143 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7144 }
7145 if (mAllowAppSwitchUids.size() > 0) {
7146 boolean printed = false;
7147 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7148 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7149 for (int j = 0; j < types.size(); j++) {
7150 if (dumpPackage == null ||
7151 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7152 if (needSep) {
7153 pw.println();
7154 needSep = false;
7155 }
7156 if (!printed) {
7157 pw.println(" mAllowAppSwitchUids:");
7158 printed = true;
7159 }
7160 pw.print(" User ");
7161 pw.print(mAllowAppSwitchUids.keyAt(i));
7162 pw.print(": Type ");
7163 pw.print(types.keyAt(j));
7164 pw.print(" = ");
7165 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7166 pw.println();
7167 }
7168 }
7169 }
7170 }
7171 if (dumpPackage == null) {
7172 if (mController != null) {
7173 pw.println(" mController=" + mController
7174 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7175 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007176 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7177 pw.println(" mLaunchingActivityWakeLock="
7178 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007179 }
7180
7181 return needSep;
7182 }
7183 }
7184
7185 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007186 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7187 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007188 synchronized (mGlobalLock) {
7189 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007190 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007191 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007192 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7193 if (mRunningVoice != null) {
7194 final long vrToken = proto.start(
7195 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7196 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7197 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007198 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007199 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7200 proto.end(vrToken);
7201 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007202 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007203 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007204 if (mController != null) {
7205 final long token = proto.start(CONTROLLER);
7206 proto.write(CONTROLLER, mController.toString());
7207 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7208 proto.end(token);
7209 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007210 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7211 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007212 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007213 }
7214
7215 if (mHomeProcess != null && (dumpPackage == null
7216 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007217 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007218 }
7219
7220 if (mPreviousProcess != null && (dumpPackage == null
7221 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007222 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7224 }
7225
7226 if (mHeavyWeightProcess != null && (dumpPackage == null
7227 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007228 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 }
7230
7231 for (Map.Entry<String, Integer> entry
7232 : mCompatModePackages.getPackages().entrySet()) {
7233 String pkg = entry.getKey();
7234 int mode = entry.getValue();
7235 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7236 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7237 proto.write(PACKAGE, pkg);
7238 proto.write(MODE, mode);
7239 proto.end(compatToken);
7240 }
7241 }
7242
7243 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007244 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007245 }
7246
7247 }
7248 }
7249
7250 @Override
7251 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7252 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7253 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007254 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7255 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007256 }
7257
7258 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007259 public void dumpForOom(PrintWriter pw) {
7260 synchronized (mGlobalLock) {
7261 pw.println(" mHomeProcess: " + mHomeProcess);
7262 pw.println(" mPreviousProcess: " + mPreviousProcess);
7263 if (mHeavyWeightProcess != null) {
7264 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7265 }
7266 }
7267 }
7268
7269 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007270 public boolean canGcNow() {
7271 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007272 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007273 }
7274 }
7275
Riddle Hsua0536432019-02-16 00:38:59 +08007276 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007277 @Override
7278 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007279 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007280 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007281 return top != null ? top.app : null;
7282 }
7283 }
7284
Riddle Hsua0536432019-02-16 00:38:59 +08007285 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007286 @Override
7287 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007288 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007289 if (mRootActivityContainer != null) {
7290 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292 }
7293 }
7294
7295 @Override
7296 public void scheduleDestroyAllActivities(String reason) {
7297 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007298 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007299 }
7300 }
7301
7302 @Override
7303 public void removeUser(int userId) {
7304 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007305 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007306 }
7307 }
7308
7309 @Override
7310 public boolean switchUser(int userId, UserState userState) {
7311 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007312 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007313 }
7314 }
7315
7316 @Override
7317 public void onHandleAppCrash(WindowProcessController wpc) {
7318 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007319 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007320 }
7321 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007322
7323 @Override
7324 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7325 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007326 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007327 }
7328 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007329
Riddle Hsua0536432019-02-16 00:38:59 +08007330 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007331 @Override
7332 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007333 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007334 }
7335
Riddle Hsua0536432019-02-16 00:38:59 +08007336 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007337 @Override
7338 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007339 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007340 }
7341
Riddle Hsua0536432019-02-16 00:38:59 +08007342 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007343 @Override
7344 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007345 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007346 }
7347
Riddle Hsua0536432019-02-16 00:38:59 +08007348 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007349 @Override
7350 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007351 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007352 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007353
7354 @Override
7355 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007356 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007357 mPendingTempWhitelist.put(uid, tag);
7358 }
7359 }
7360
7361 @Override
7362 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007363 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007364 mPendingTempWhitelist.remove(uid);
7365 }
7366 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007367
7368 @Override
7369 public boolean handleAppCrashInActivityController(String processName, int pid,
7370 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7371 Runnable killCrashingAppCallback) {
7372 synchronized (mGlobalLock) {
7373 if (mController == null) {
7374 return false;
7375 }
7376
7377 try {
7378 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7379 stackTrace)) {
7380 killCrashingAppCallback.run();
7381 return true;
7382 }
7383 } catch (RemoteException e) {
7384 mController = null;
7385 Watchdog.getInstance().setActivityController(null);
7386 }
7387 return false;
7388 }
7389 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007390
7391 @Override
7392 public void removeRecentTasksByPackageName(String packageName, int userId) {
7393 synchronized (mGlobalLock) {
7394 mRecentTasks.removeTasksByPackageName(packageName, userId);
7395 }
7396 }
7397
7398 @Override
7399 public void cleanupRecentTasksForUser(int userId) {
7400 synchronized (mGlobalLock) {
7401 mRecentTasks.cleanupLocked(userId);
7402 }
7403 }
7404
7405 @Override
7406 public void loadRecentTasksForUser(int userId) {
7407 synchronized (mGlobalLock) {
7408 mRecentTasks.loadUserRecentsLocked(userId);
7409 }
7410 }
7411
7412 @Override
7413 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7414 synchronized (mGlobalLock) {
7415 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7416 }
7417 }
7418
7419 @Override
7420 public void flushRecentTasks() {
7421 mRecentTasks.flush();
7422 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007423
7424 @Override
7425 public WindowProcessController getHomeProcess() {
7426 synchronized (mGlobalLock) {
7427 return mHomeProcess;
7428 }
7429 }
7430
7431 @Override
7432 public WindowProcessController getPreviousProcess() {
7433 synchronized (mGlobalLock) {
7434 return mPreviousProcess;
7435 }
7436 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007437
7438 @Override
7439 public void clearLockedTasks(String reason) {
7440 synchronized (mGlobalLock) {
7441 getLockTaskController().clearLockedTasks(reason);
7442 }
7443 }
7444
7445 @Override
7446 public void updateUserConfiguration() {
7447 synchronized (mGlobalLock) {
7448 final Configuration configuration = new Configuration(getGlobalConfiguration());
7449 final int currentUserId = mAmInternal.getCurrentUserId();
7450 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7451 configuration, currentUserId, Settings.System.canWrite(mContext));
7452 updateConfigurationLocked(configuration, null /* starting */,
7453 false /* initLocale */, false /* persistent */, currentUserId,
7454 false /* deferResume */);
7455 }
7456 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007457
7458 @Override
7459 public boolean canShowErrorDialogs() {
7460 synchronized (mGlobalLock) {
7461 return mShowDialogs && !mSleeping && !mShuttingDown
7462 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7463 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7464 mAmInternal.getCurrentUserId())
7465 && !(UserManager.isDeviceInDemoMode(mContext)
7466 && mAmInternal.getCurrentUser().isDemo());
7467 }
7468 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007469
7470 @Override
7471 public void setProfileApp(String profileApp) {
7472 synchronized (mGlobalLock) {
7473 mProfileApp = profileApp;
7474 }
7475 }
7476
7477 @Override
7478 public void setProfileProc(WindowProcessController wpc) {
7479 synchronized (mGlobalLock) {
7480 mProfileProc = wpc;
7481 }
7482 }
7483
7484 @Override
7485 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7486 synchronized (mGlobalLock) {
7487 mProfilerInfo = profilerInfo;
7488 }
7489 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007490
7491 @Override
7492 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7493 synchronized (mGlobalLock) {
7494 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7495 }
7496 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007497
7498 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007499 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7500 boolean reducedResolution) {
7501 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7502 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007503 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007504
7505 @Override
7506 public boolean isUidForeground(int uid) {
7507 synchronized (mGlobalLock) {
7508 return ActivityTaskManagerService.this.isUidForeground(uid);
7509 }
7510 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007511
7512 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007513 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007514 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007515 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007516 }
7517 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007518
7519 @Override
7520 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007521 // Translate package names into UIDs
7522 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007523 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007524 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7525 if (uid >= 0) {
7526 result.add(uid);
7527 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007528 }
7529 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007530 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007531 }
7532 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007533 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007534}