blob: 6f80feb580c2aa09317b4d319ae13adf22fce101 [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 Ogunwale196db712019-12-27 15:35:39 +0000309 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700310 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
311 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
312 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
313 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700314 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700315
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100320 // How long we permit background activity starts after an activity in the process
321 // started or finished.
322 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700323
Wale Ogunwale98875612018-10-12 07:53:02 -0700324 /** Used to indicate that an app transition should be animated. */
325 static final boolean ANIMATE = true;
326
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700327 /** Hardware-reported OpenGLES version. */
328 final int GL_ES_VERSION;
329
Wale Ogunwale31913b52018-10-13 08:29:31 -0700330 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
331 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
332 public static final String DUMP_LASTANR_CMD = "lastanr" ;
333 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
334 public static final String DUMP_STARTER_CMD = "starter" ;
335 public static final String DUMP_CONTAINERS_CMD = "containers" ;
336 public static final String DUMP_RECENTS_CMD = "recents" ;
337 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
338
Wale Ogunwale64258362018-10-16 15:13:37 -0700339 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
340 public static final int RELAUNCH_REASON_NONE = 0;
341 /** This activity is being relaunched due to windowing mode change. */
342 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
343 /** This activity is being relaunched due to a free-resize operation. */
344 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
345
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700346 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700347
Wale Ogunwalef6733932018-06-27 05:14:34 -0700348 /**
349 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
350 * change at runtime. Use mContext for non-UI purposes.
351 */
352 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700358 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800359 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800360 @VisibleForTesting
361 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 PowerManagerInternal mPowerManagerInternal;
363 private UsageStatsManagerInternal mUsageStatsInternal;
364
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700365 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 IntentFirewall mIntentFirewall;
367
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700368 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800369 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700371 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
373 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
374 *
375 * @see WindowManagerThreadPriorityBooster
376 */
377 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 ActivityStackSupervisor mStackSupervisor;
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 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700830 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700832 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700834 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700836 mKeyguardController = mStackSupervisor.getKeyguardController();
837 }
838
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700839 public void onActivityManagerInternalAdded() {
840 synchronized (mGlobalLock) {
841 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
842 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
843 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700844 }
845
Yunfan Chen75157d72018-07-27 14:47:21 +0900846 int increaseConfigurationSeqLocked() {
847 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
848 return mConfigurationSeq;
849 }
850
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700851 protected ActivityStackSupervisor createStackSupervisor() {
852 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
853 supervisor.initialize();
854 return supervisor;
855 }
856
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800857 protected AppWarnings createAppWarnings(
858 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
859 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
860 }
861
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700862 public void setWindowManager(WindowManagerService wm) {
863 synchronized (mGlobalLock) {
864 mWindowManager = wm;
Louis Chang3ff72a82019-12-17 12:12:59 +0800865 // TODO(merge-root): Remove cast
866 mRootActivityContainer = (RootActivityContainer) wm.mRoot;
867 mTempConfig.setToDefaults();
868 mTempConfig.setLocales(LocaleList.getDefault());
869 mConfigurationSeq = mTempConfig.seq = 1;
870 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700871 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 Ogunwale196db712019-12-27 15:35:39 +00001733 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1734 if (r != null) {
1735 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 }
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 Ogunwale196db712019-12-27 15:35:39 +00001768 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001769 }
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() {
Louis Chang3ff72a82019-12-17 12:12:59 +08005219 // Return default configuration before mRootActivityContainer initialized, which happens
5220 // while initializing process record for system, see {@link
5221 // ActivityManagerService#setSystemProcess}.
5222 return mRootActivityContainer != null ? mRootActivityContainer.getConfiguration()
5223 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 }
5225
5226 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5227 boolean initLocale) {
5228 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5229 }
5230
5231 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5232 boolean initLocale, boolean deferResume) {
5233 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5234 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5235 UserHandle.USER_NULL, deferResume);
5236 }
5237
Wale Ogunwale59507092018-10-29 09:00:30 -07005238 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005239 final long origId = Binder.clearCallingIdentity();
5240 try {
5241 synchronized (mGlobalLock) {
5242 updateConfigurationLocked(values, null, false, true, userId,
5243 false /* deferResume */);
5244 }
5245 } finally {
5246 Binder.restoreCallingIdentity(origId);
5247 }
5248 }
5249
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005250 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5251 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5252 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5253 deferResume, null /* result */);
5254 }
5255
5256 /**
5257 * Do either or both things: (1) change the current configuration, and (2)
5258 * make sure the given activity is running with the (now) current
5259 * configuration. Returns true if the activity has been left running, or
5260 * false if <var>starting</var> is being destroyed to match the new
5261 * configuration.
5262 *
5263 * @param userId is only used when persistent parameter is set to true to persist configuration
5264 * for that particular user
5265 */
5266 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5267 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5268 ActivityTaskManagerService.UpdateConfigurationResult result) {
5269 int changes = 0;
5270 boolean kept = true;
5271
Riddle Hsua0022cd2019-09-09 21:12:41 +08005272 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273 try {
5274 if (values != null) {
5275 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5276 deferResume);
5277 }
5278
5279 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5280 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005281 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005282 }
5283
5284 if (result != null) {
5285 result.changes = changes;
5286 result.activityRelaunched = !kept;
5287 }
5288 return kept;
5289 }
5290
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005291 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005292 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005293 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005294
Louis Chang677921f2019-12-06 16:44:24 +08005295 final DisplayContent defaultDisplay =
5296 mRootActivityContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005297
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298 mTempConfig.setTo(getGlobalConfiguration());
5299 final int changes = mTempConfig.updateFrom(values);
5300 if (changes == 0) {
5301 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5302 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5303 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5304 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005305 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005306 return 0;
5307 }
5308
5309 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5310 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005311 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005312 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5313 values.colorMode,
5314 values.densityDpi,
5315 values.fontScale,
5316 values.hardKeyboardHidden,
5317 values.keyboard,
5318 values.keyboardHidden,
5319 values.mcc,
5320 values.mnc,
5321 values.navigation,
5322 values.navigationHidden,
5323 values.orientation,
5324 values.screenHeightDp,
5325 values.screenLayout,
5326 values.screenWidthDp,
5327 values.smallestScreenWidthDp,
5328 values.touchscreen,
5329 values.uiMode);
5330
5331
5332 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5333 final LocaleList locales = values.getLocales();
5334 int bestLocaleIndex = 0;
5335 if (locales.size() > 1) {
5336 if (mSupportedSystemLocales == null) {
5337 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5338 }
5339 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5340 }
5341 SystemProperties.set("persist.sys.locale",
5342 locales.get(bestLocaleIndex).toLanguageTag());
5343 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005344
5345 final Message m = PooledLambda.obtainMessage(
5346 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5347 locales.get(bestLocaleIndex));
5348 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005349 }
5350
Yunfan Chen75157d72018-07-27 14:47:21 +09005351 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005352
5353 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005354 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005355
5356 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5357 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005358 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005359
5360 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005361 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005362
5363 AttributeCache ac = AttributeCache.instance();
5364 if (ac != null) {
5365 ac.updateConfiguration(mTempConfig);
5366 }
5367
5368 // Make sure all resources in our process are updated right now, so that anyone who is going
5369 // to retrieve resource values after we return will be sure to get the new ones. This is
5370 // especially important during boot, where the first config change needs to guarantee all
5371 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005372 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005373
5374 // We need another copy of global config because we're scheduling some calls instead of
5375 // running them in place. We need to be sure that object we send will be handled unchanged.
5376 final Configuration configCopy = new Configuration(mTempConfig);
5377 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005378 final Message msg = PooledLambda.obtainMessage(
5379 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5380 this, userId, configCopy);
5381 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005382 }
5383
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005384 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5385 for (int i = pidMap.size() - 1; i >= 0; i--) {
5386 final int pid = pidMap.keyAt(i);
5387 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005388 if (DEBUG_CONFIGURATION) {
5389 Slog.v(TAG_CONFIGURATION, "Update process config of "
5390 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005391 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005392 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005393 }
5394
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005395 final Message msg = PooledLambda.obtainMessage(
5396 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5397 mAmInternal, changes, initLocale);
5398 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005399
5400 // Override configuration of the default display duplicates global config, so we need to
5401 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005402 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5403 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005404
5405 return changes;
5406 }
5407
Riddle Hsua0022cd2019-09-09 21:12:41 +08005408 /** @see WindowSurfacePlacer#deferLayout */
5409 void deferWindowLayout() {
5410 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5411 // Reset the reasons at the first entrance because we only care about the changes in the
5412 // deferred scope.
5413 mLayoutReasons = 0;
5414 }
5415
5416 mWindowManager.mWindowPlacerLocked.deferLayout();
5417 }
5418
5419 /** @see WindowSurfacePlacer#continueLayout */
5420 void continueWindowLayout() {
5421 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5422 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5423 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5424 }
5425 }
5426
5427 /**
5428 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5429 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5430 * defer count is gone.
5431 */
5432 void addWindowLayoutReasons(@LayoutReason int reasons) {
5433 mLayoutReasons |= reasons;
5434 }
5435
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 private void updateEventDispatchingLocked(boolean booted) {
5437 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5438 }
5439
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005440 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5441 final ContentResolver resolver = mContext.getContentResolver();
5442 Settings.System.putConfigurationForUser(resolver, config, userId);
5443 }
5444
5445 private void sendLocaleToMountDaemonMsg(Locale l) {
5446 try {
5447 IBinder service = ServiceManager.getService("mount");
5448 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5449 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5450 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5451 } catch (RemoteException e) {
5452 Log.e(TAG, "Error storing locale for decryption UI", e);
5453 }
5454 }
5455
Alison Cichowlas3e340502018-08-07 17:15:01 -04005456 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5457 mStartActivitySources.remove(permissionToken);
5458 mExpiredStartAsCallerTokens.add(permissionToken);
5459 }
5460
5461 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5462 mExpiredStartAsCallerTokens.remove(permissionToken);
5463 }
5464
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005465 boolean isActivityStartsLoggingEnabled() {
5466 return mAmInternal.isActivityStartsLoggingEnabled();
5467 }
5468
Michal Karpinski8596ded2018-11-14 14:43:48 +00005469 boolean isBackgroundActivityStartsEnabled() {
5470 return mAmInternal.isBackgroundActivityStartsEnabled();
5471 }
5472
Wale Ogunwalef6733932018-06-27 05:14:34 -07005473 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005474 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005475 mWindowManager.enableScreenAfterBoot();
5476
5477 synchronized (mGlobalLock) {
5478 updateEventDispatchingLocked(booted);
5479 }
5480 }
5481
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005482 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5483 if (r == null || !r.hasProcess()) {
5484 return KEY_DISPATCHING_TIMEOUT_MS;
5485 }
5486 return getInputDispatchingTimeoutLocked(r.app);
5487 }
5488
5489 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005490 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005491 }
5492
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 /**
5494 * Decide based on the configuration whether we should show the ANR,
5495 * crash, etc dialogs. The idea is that if there is no affordance to
5496 * press the on-screen buttons, or the user experience would be more
5497 * greatly impacted than the crash itself, we shouldn't show the dialog.
5498 *
5499 * A thought: SystemUI might also want to get told about this, the Power
5500 * dialog / global actions also might want different behaviors.
5501 */
5502 private void updateShouldShowDialogsLocked(Configuration config) {
5503 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5504 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5505 && config.navigation == Configuration.NAVIGATION_NONAV);
5506 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5507 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5508 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5509 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5510 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5511 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5512 HIDE_ERROR_DIALOGS, 0) != 0;
5513 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5514 }
5515
5516 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5517 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5518 FONT_SCALE, 1.0f, userId);
5519
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005520 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005521 if (getGlobalConfiguration().fontScale == scaleFactor) {
5522 return;
5523 }
5524
5525 final Configuration configuration
5526 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5527 configuration.fontScale = scaleFactor;
5528 updatePersistentConfiguration(configuration, userId);
5529 }
5530 }
5531
5532 // Actually is sleeping or shutting down or whatever else in the future
5533 // is an inactive state.
5534 boolean isSleepingOrShuttingDownLocked() {
5535 return isSleepingLocked() || mShuttingDown;
5536 }
5537
5538 boolean isSleepingLocked() {
5539 return mSleeping;
5540 }
5541
Riddle Hsu16567132018-08-16 21:37:47 +08005542 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005544 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 if (task.isActivityTypeStandard()) {
5546 if (mCurAppTimeTracker != r.appTimeTracker) {
5547 // We are switching app tracking. Complete the current one.
5548 if (mCurAppTimeTracker != null) {
5549 mCurAppTimeTracker.stop();
5550 mH.obtainMessage(
5551 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005552 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005553 mCurAppTimeTracker = null;
5554 }
5555 if (r.appTimeTracker != null) {
5556 mCurAppTimeTracker = r.appTimeTracker;
5557 startTimeTrackingFocusedActivityLocked();
5558 }
5559 } else {
5560 startTimeTrackingFocusedActivityLocked();
5561 }
5562 } else {
5563 r.appTimeTracker = null;
5564 }
5565 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5566 // TODO: Probably not, because we don't want to resume voice on switching
5567 // back to this activity
5568 if (task.voiceInteractor != null) {
5569 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5570 } else {
5571 finishRunningVoiceLocked();
5572
5573 if (mLastResumedActivity != null) {
5574 final IVoiceInteractionSession session;
5575
Louis Changcdec0802019-11-11 11:45:07 +08005576 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005577 if (lastResumedActivityTask != null
5578 && lastResumedActivityTask.voiceSession != null) {
5579 session = lastResumedActivityTask.voiceSession;
5580 } else {
5581 session = mLastResumedActivity.voiceSession;
5582 }
5583
5584 if (session != null) {
5585 // We had been in a voice interaction session, but now focused has
5586 // move to something different. Just finish the session, we can't
5587 // return to it and retain the proper state and synchronization with
5588 // the voice interaction service.
5589 finishVoiceTask(session);
5590 }
5591 }
5592 }
5593
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005594 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5595 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005596 }
5597 updateResumedAppTrace(r);
5598 mLastResumedActivity = r;
5599
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005600 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601
5602 applyUpdateLockStateLocked(r);
5603 applyUpdateVrModeLocked(r);
5604
Jeff Changd136e772019-11-05 20:33:52 +08005605 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005606 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005607 r == null ? "NULL" : r.shortComponentName,
5608 reason);
5609 }
5610
5611 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5612 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005613 final ActivityTaskManagerInternal.SleepToken token =
5614 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005615 updateSleepIfNeededLocked();
5616 return token;
5617 }
5618 }
5619
5620 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005621 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005622 final boolean wasSleeping = mSleeping;
5623 boolean updateOomAdj = false;
5624
5625 if (!shouldSleep) {
5626 // If wasSleeping is true, we need to wake up activity manager state from when
5627 // we started sleeping. In either case, we need to apply the sleep tokens, which
5628 // will wake up stacks or put them to sleep as appropriate.
5629 if (wasSleeping) {
5630 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005631 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5632 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005633 startTimeTrackingFocusedActivityLocked();
5634 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005635 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005636 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5637 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005638 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005639 if (wasSleeping) {
5640 updateOomAdj = true;
5641 }
5642 } else if (!mSleeping && shouldSleep) {
5643 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005644 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5645 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005646 if (mCurAppTimeTracker != null) {
5647 mCurAppTimeTracker.stop();
5648 }
5649 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005650 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005651 mStackSupervisor.goingToSleepLocked();
5652 updateResumedAppTrace(null /* resumed */);
5653 updateOomAdj = true;
5654 }
5655 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005656 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005657 }
5658 }
5659
5660 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005661 mH.removeCallbacks(mUpdateOomAdjRunnable);
5662 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005663 }
5664
Wale Ogunwale53783742018-09-16 10:21:51 -07005665 void updateCpuStats() {
5666 mH.post(mAmInternal::updateCpuStats);
5667 }
5668
Hui Yu03d12402018-12-06 18:00:37 -08005669 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5670 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005671 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5672 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005673 mH.sendMessage(m);
5674 }
5675
Hui Yu03d12402018-12-06 18:00:37 -08005676 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005677 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005678 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005679 if (task != null) {
5680 final ActivityRecord rootActivity = task.getRootActivity();
5681 if (rootActivity != null) {
5682 taskRoot = rootActivity.mActivityComponent;
5683 }
5684 }
5685
Hui Yu03d12402018-12-06 18:00:37 -08005686 final Message m = PooledLambda.obtainMessage(
5687 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005688 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005689 mH.sendMessage(m);
5690 }
5691
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005692 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5693 String hostingType) {
5694 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005695 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5696 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005697 + activity.processName);
5698 }
5699 // Post message to start process to avoid possible deadlock of calling into AMS with the
5700 // ATMS lock held.
5701 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5702 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5703 isTop, hostingType, activity.intent.getComponent());
5704 mH.sendMessage(m);
5705 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005706 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005707 }
5708 }
5709
Wale Ogunwale53783742018-09-16 10:21:51 -07005710 void setBooting(boolean booting) {
5711 mAmInternal.setBooting(booting);
5712 }
5713
5714 boolean isBooting() {
5715 return mAmInternal.isBooting();
5716 }
5717
5718 void setBooted(boolean booted) {
5719 mAmInternal.setBooted(booted);
5720 }
5721
5722 boolean isBooted() {
5723 return mAmInternal.isBooted();
5724 }
5725
5726 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5727 mH.post(() -> {
5728 if (finishBooting) {
5729 mAmInternal.finishBooting();
5730 }
5731 if (enableScreen) {
5732 mInternal.enableScreenAfterBoot(isBooted());
5733 }
5734 });
5735 }
5736
5737 void setHeavyWeightProcess(ActivityRecord root) {
5738 mHeavyWeightProcess = root.app;
5739 final Message m = PooledLambda.obtainMessage(
5740 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005741 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005742 mH.sendMessage(m);
5743 }
5744
5745 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5746 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5747 return;
5748 }
5749
5750 mHeavyWeightProcess = null;
5751 final Message m = PooledLambda.obtainMessage(
5752 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5753 proc.mUserId);
5754 mH.sendMessage(m);
5755 }
5756
5757 private void cancelHeavyWeightProcessNotification(int userId) {
5758 final INotificationManager inm = NotificationManager.getService();
5759 if (inm == null) {
5760 return;
5761 }
5762 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005763 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005764 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5765 } catch (RuntimeException e) {
5766 Slog.w(TAG, "Error canceling notification for service", e);
5767 } catch (RemoteException e) {
5768 }
5769
5770 }
5771
5772 private void postHeavyWeightProcessNotification(
5773 WindowProcessController proc, Intent intent, int userId) {
5774 if (proc == null) {
5775 return;
5776 }
5777
5778 final INotificationManager inm = NotificationManager.getService();
5779 if (inm == null) {
5780 return;
5781 }
5782
5783 try {
5784 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5785 String text = mContext.getString(R.string.heavy_weight_notification,
5786 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5787 Notification notification =
5788 new Notification.Builder(context,
5789 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5790 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5791 .setWhen(0)
5792 .setOngoing(true)
5793 .setTicker(text)
5794 .setColor(mContext.getColor(
5795 com.android.internal.R.color.system_notification_accent_color))
5796 .setContentTitle(text)
5797 .setContentText(
5798 mContext.getText(R.string.heavy_weight_notification_detail))
5799 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5800 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5801 new UserHandle(userId)))
5802 .build();
5803 try {
5804 inm.enqueueNotificationWithTag("android", "android", null,
5805 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5806 } catch (RuntimeException e) {
5807 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5808 } catch (RemoteException e) {
5809 }
5810 } catch (PackageManager.NameNotFoundException e) {
5811 Slog.w(TAG, "Unable to create context for heavy notification", e);
5812 }
5813
5814 }
5815
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005816 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5817 IBinder token, String resultWho, int requestCode, Intent[] intents,
5818 String[] resolvedTypes, int flags, Bundle bOptions) {
5819
5820 ActivityRecord activity = null;
5821 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5822 activity = ActivityRecord.isInStackLocked(token);
5823 if (activity == null) {
5824 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5825 return null;
5826 }
5827 if (activity.finishing) {
5828 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5829 return null;
5830 }
5831 }
5832
5833 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5834 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5835 bOptions);
5836 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5837 if (noCreate) {
5838 return rec;
5839 }
5840 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5841 if (activity.pendingResults == null) {
5842 activity.pendingResults = new HashSet<>();
5843 }
5844 activity.pendingResults.add(rec.ref);
5845 }
5846 return rec;
5847 }
5848
Andrii Kulian52d255c2018-07-13 11:32:19 -07005849 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005850 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005851 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005852 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5853 mCurAppTimeTracker.start(resumedActivity.packageName);
5854 }
5855 }
5856
5857 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5858 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005859 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005860 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5861 }
5862 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005863 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005864 constructResumedTraceName(resumed.packageName), 0);
5865 }
5866 mTracedResumedActivity = resumed;
5867 }
5868
5869 private String constructResumedTraceName(String packageName) {
5870 return "focused app: " + packageName;
5871 }
5872
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005873 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005874 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005875 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005876 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005877 // mainStack is null during startup.
5878 if (mainStack != null) {
5879 if (changes != 0 && starting == null) {
5880 // If the configuration changed, and the caller is not already
5881 // in the process of starting an activity, then find the top
5882 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005883 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005884 }
5885
5886 if (starting != null) {
5887 kept = starting.ensureActivityConfiguration(changes,
5888 false /* preserveWindow */);
5889 // And we need to make sure at this point that all other activities
5890 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005891 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005892 !PRESERVE_WINDOWS);
5893 }
5894 }
5895
5896 return kept;
5897 }
5898
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005899 void scheduleAppGcsLocked() {
5900 mH.post(() -> mAmInternal.scheduleAppGcs());
5901 }
5902
Wale Ogunwale53783742018-09-16 10:21:51 -07005903 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5904 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5905 }
5906
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005907 /**
5908 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5909 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5910 * on demand.
5911 */
5912 IPackageManager getPackageManager() {
5913 return AppGlobals.getPackageManager();
5914 }
5915
5916 PackageManagerInternal getPackageManagerInternalLocked() {
5917 if (mPmInternal == null) {
5918 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5919 }
5920 return mPmInternal;
5921 }
5922
Hai Zhangf4da9be2019-05-01 13:46:06 +08005923 PermissionPolicyInternal getPermissionPolicyInternal() {
5924 if (mPermissionPolicyInternal == null) {
5925 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5926 }
5927 return mPermissionPolicyInternal;
5928 }
5929
Wale Ogunwale008163e2018-07-23 23:11:08 -07005930 AppWarnings getAppWarningsLocked() {
5931 return mAppWarnings;
5932 }
5933
Wale Ogunwale214f3482018-10-04 11:00:47 -07005934 Intent getHomeIntent() {
5935 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5936 intent.setComponent(mTopComponent);
5937 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5938 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5939 intent.addCategory(Intent.CATEGORY_HOME);
5940 }
5941 return intent;
5942 }
5943
Chilun2ef71f72018-11-16 17:57:15 +08005944 /**
5945 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5946 * activities.
5947 *
5948 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5949 * component defined in config_secondaryHomeComponent.
5950 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5951 */
5952 Intent getSecondaryHomeIntent(String preferredPackage) {
5953 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005954 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5955 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5956 if (preferredPackage == null || useSystemProvidedLauncher) {
5957 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005958 final String secondaryHomeComponent = mContext.getResources().getString(
5959 com.android.internal.R.string.config_secondaryHomeComponent);
5960 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5961 } else {
5962 intent.setPackage(preferredPackage);
5963 }
5964 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5965 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5966 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5967 }
5968 return intent;
5969 }
5970
Wale Ogunwale214f3482018-10-04 11:00:47 -07005971 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5972 if (info == null) return null;
5973 ApplicationInfo newInfo = new ApplicationInfo(info);
5974 newInfo.initForUser(userId);
5975 return newInfo;
5976 }
5977
Wale Ogunwale9c103022018-10-18 07:44:54 -07005978 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005979 if (uid == SYSTEM_UID) {
5980 // The system gets to run in any process. If there are multiple processes with the same
5981 // uid, just pick the first (this should never happen).
5982 final SparseArray<WindowProcessController> procs =
5983 mProcessNames.getMap().get(processName);
5984 if (procs == null) return null;
5985 final int procCount = procs.size();
5986 for (int i = 0; i < procCount; i++) {
5987 final int procUid = procs.keyAt(i);
5988 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5989 // Don't use an app process or different user process for system component.
5990 continue;
5991 }
5992 return procs.valueAt(i);
5993 }
5994 }
5995
5996 return mProcessNames.get(processName, uid);
5997 }
5998
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005999 WindowProcessController getProcessController(IApplicationThread thread) {
6000 if (thread == null) {
6001 return null;
6002 }
6003
6004 final IBinder threadBinder = thread.asBinder();
6005 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6006 for (int i = pmap.size()-1; i >= 0; i--) {
6007 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6008 for (int j = procs.size() - 1; j >= 0; j--) {
6009 final WindowProcessController proc = procs.valueAt(j);
6010 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6011 return proc;
6012 }
6013 }
6014 }
6015
6016 return null;
6017 }
6018
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006019 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006020 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006021 if (proc == null) return null;
6022 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6023 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006024 }
6025 return null;
6026 }
6027
Riddle Hsua0536432019-02-16 00:38:59 +08006028 int getUidState(int uid) {
6029 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006030 }
6031
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006032 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006033 // A uid is considered to be foreground if it has a visible non-toast window.
6034 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006035 }
6036
Ricky Wai96f5c352019-04-10 18:40:17 +01006037 boolean isDeviceOwner(int uid) {
6038 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006039 }
6040
Ricky Wai96f5c352019-04-10 18:40:17 +01006041 void setDeviceOwnerUid(int uid) {
6042 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006043 }
6044
Wale Ogunwale9de19442018-10-18 19:05:03 -07006045 /**
6046 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6047 * the whitelist
6048 */
6049 String getPendingTempWhitelistTagForUidLocked(int uid) {
6050 return mPendingTempWhitelist.get(uid);
6051 }
6052
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006053 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6054 if (true || Build.IS_USER) {
6055 return;
6056 }
6057
6058 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6059 StrictMode.allowThreadDiskWrites();
6060 try {
6061 File tracesDir = new File("/data/anr");
6062 File tracesFile = null;
6063 try {
6064 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6065
6066 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006067 String timeString =
6068 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6069 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006070 sb.append(": ");
6071 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6072 sb.append(" since ");
6073 sb.append(msg);
6074 FileOutputStream fos = new FileOutputStream(tracesFile);
6075 fos.write(sb.toString().getBytes());
6076 if (app == null) {
6077 fos.write("\n*** No application process!".getBytes());
6078 }
6079 fos.close();
6080 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6081 } catch (IOException e) {
6082 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6083 return;
6084 }
6085
6086 if (app != null && app.getPid() > 0) {
6087 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6088 firstPids.add(app.getPid());
6089 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6090 }
6091
6092 File lastTracesFile = null;
6093 File curTracesFile = null;
6094 for (int i=9; i>=0; i--) {
6095 String name = String.format(Locale.US, "slow%02d.txt", i);
6096 curTracesFile = new File(tracesDir, name);
6097 if (curTracesFile.exists()) {
6098 if (lastTracesFile != null) {
6099 curTracesFile.renameTo(lastTracesFile);
6100 } else {
6101 curTracesFile.delete();
6102 }
6103 }
6104 lastTracesFile = curTracesFile;
6105 }
6106 tracesFile.renameTo(curTracesFile);
6107 } finally {
6108 StrictMode.setThreadPolicy(oldPolicy);
6109 }
6110 }
6111
Michal Karpinskida34cd42019-04-02 19:46:52 +01006112 boolean isAssociatedCompanionApp(int userId, int uid) {
6113 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6114 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006115 return false;
6116 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006117 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006118 }
6119
Issei Suzuki734bc942019-06-05 13:59:52 +02006120 void notifySingleTaskDisplayEmpty(int displayId) {
6121 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6122 }
6123
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006124 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006125 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006126
6127
Wale Ogunwale98875612018-10-12 07:53:02 -07006128 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6129 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006130
Riddle Hsud93a6c42018-11-29 21:50:06 +08006131 H(Looper looper) {
6132 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006133 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006134
6135 @Override
6136 public void handleMessage(Message msg) {
6137 switch (msg.what) {
6138 case REPORT_TIME_TRACKER_MSG: {
6139 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6140 tracker.deliverResult(mContext);
6141 } break;
6142 }
6143 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006144 }
6145
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006146 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006147 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006148
6149 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006150 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006151 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006152
6153 @Override
6154 public void handleMessage(Message msg) {
6155 switch (msg.what) {
6156 case DISMISS_DIALOG_UI_MSG: {
6157 final Dialog d = (Dialog) msg.obj;
6158 d.dismiss();
6159 break;
6160 }
6161 }
6162 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006163 }
6164
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006165 final class LocalService extends ActivityTaskManagerInternal {
6166 @Override
6167 public SleepToken acquireSleepToken(String tag, int displayId) {
6168 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006169 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006170 }
6171
6172 @Override
6173 public ComponentName getHomeActivityForUser(int userId) {
6174 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006175 final ActivityRecord homeActivity =
6176 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006177 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179 }
6180
6181 @Override
6182 public void onLocalVoiceInteractionStarted(IBinder activity,
6183 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6184 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006185 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 }
6187 }
6188
6189 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006190 public void notifySingleTaskDisplayDrawn(int displayId) {
6191 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6192 }
6193
6194 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006195 public void notifyAppTransitionFinished() {
6196 synchronized (mGlobalLock) {
6197 mStackSupervisor.notifyAppTransitionDone();
6198 }
6199 }
6200
6201 @Override
6202 public void notifyAppTransitionCancelled() {
6203 synchronized (mGlobalLock) {
6204 mStackSupervisor.notifyAppTransitionDone();
6205 }
6206 }
6207
6208 @Override
6209 public List<IBinder> getTopVisibleActivities() {
6210 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006211 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006212 }
6213 }
6214
6215 @Override
6216 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6217 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006218 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006219 }
6220 }
6221
6222 @Override
6223 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6224 Bundle bOptions) {
6225 Preconditions.checkNotNull(intents, "intents");
6226 final String[] resolvedTypes = new String[intents.length];
6227
6228 // UID of the package on user userId.
6229 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6230 // packageUid may not be initialized.
6231 int packageUid = 0;
6232 final long ident = Binder.clearCallingIdentity();
6233
6234 try {
6235 for (int i = 0; i < intents.length; i++) {
6236 resolvedTypes[i] =
6237 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6238 }
6239
6240 packageUid = AppGlobals.getPackageManager().getPackageUid(
6241 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6242 } catch (RemoteException e) {
6243 // Shouldn't happen.
6244 } finally {
6245 Binder.restoreCallingIdentity(ident);
6246 }
6247
Riddle Hsu591bf612019-02-14 17:55:31 +08006248 return getActivityStartController().startActivitiesInPackage(
6249 packageUid, packageName,
6250 intents, resolvedTypes, null /* resultTo */,
6251 SafeActivityOptions.fromBundle(bOptions), userId,
6252 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6253 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 }
6255
6256 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006257 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6258 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6259 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6260 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006261 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006262 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006263 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6264 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6265 userId, validateIncomingUser, originatingPendingIntent,
6266 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006267 }
6268 }
6269
6270 @Override
6271 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6272 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6273 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006274 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006275 PendingIntentRecord originatingPendingIntent,
6276 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006277 synchronized (mGlobalLock) {
6278 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6279 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6280 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006281 validateIncomingUser, originatingPendingIntent,
6282 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006283 }
6284 }
6285
6286 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006287 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6288 Intent intent, Bundle options, int userId) {
6289 return ActivityTaskManagerService.this.startActivityAsUser(
6290 caller, callerPacakge, intent,
6291 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6292 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6293 false /*validateIncomingUser*/);
6294 }
6295
6296 @Override
lumark588a3e82018-07-20 18:53:54 +08006297 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006298 synchronized (mGlobalLock) {
6299
6300 // We might change the visibilities here, so prepare an empty app transition which
6301 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006302 final DisplayContent displayContent =
6303 mRootActivityContainer.getDisplayContent(displayId);
6304 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006305 return;
6306 }
Louis Chang677921f2019-12-06 16:44:24 +08006307 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006308 final boolean wasTransitionSet =
6309 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006310 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006311 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006312 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006313 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006314
6315 // If there was a transition set already we don't want to interfere with it as we
6316 // might be starting it too early.
6317 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006318 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006319 }
6320 }
6321 if (callback != null) {
6322 callback.run();
6323 }
6324 }
6325
6326 @Override
6327 public void notifyKeyguardTrustedChanged() {
6328 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006329 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006330 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006331 }
6332 }
6333 }
6334
6335 /**
6336 * Called after virtual display Id is updated by
6337 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6338 * {@param vrVr2dDisplayId}.
6339 */
6340 @Override
6341 public void setVr2dDisplayId(int vr2dDisplayId) {
6342 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6343 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006344 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006345 }
6346 }
6347
6348 @Override
6349 public void setFocusedActivity(IBinder token) {
6350 synchronized (mGlobalLock) {
6351 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6352 if (r == null) {
6353 throw new IllegalArgumentException(
6354 "setFocusedActivity: No activity record matching token=" + token);
6355 }
Louis Chang19443452018-10-09 12:10:21 +08006356 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006357 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006358 }
6359 }
6360 }
6361
6362 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006363 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006364 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006365 }
6366
6367 @Override
6368 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006369 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006370 }
6371
6372 @Override
6373 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006374 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006375 }
6376
6377 @Override
6378 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6379 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6380 }
6381
6382 @Override
6383 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006384 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006385 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006386
6387 @Override
6388 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6389 synchronized (mGlobalLock) {
6390 mActiveVoiceInteractionServiceComponent = component;
6391 }
6392 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006393
6394 @Override
6395 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6396 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6397 return;
6398 }
6399 synchronized (mGlobalLock) {
6400 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6401 if (types == null) {
6402 if (uid < 0) {
6403 return;
6404 }
6405 types = new ArrayMap<>();
6406 mAllowAppSwitchUids.put(userId, types);
6407 }
6408 if (uid < 0) {
6409 types.remove(type);
6410 } else {
6411 types.put(type, uid);
6412 }
6413 }
6414 }
6415
6416 @Override
6417 public void onUserStopped(int userId) {
6418 synchronized (mGlobalLock) {
6419 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6420 mAllowAppSwitchUids.remove(userId);
6421 }
6422 }
6423
6424 @Override
6425 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6426 synchronized (mGlobalLock) {
6427 return ActivityTaskManagerService.this.isGetTasksAllowed(
6428 caller, callingPid, callingUid);
6429 }
6430 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006431
Riddle Hsua0536432019-02-16 00:38:59 +08006432 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006433 @Override
6434 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006435 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006436 mProcessNames.put(proc.mName, proc.mUid, proc);
6437 }
6438 }
6439
Riddle Hsua0536432019-02-16 00:38:59 +08006440 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006441 @Override
6442 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006443 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006444 mProcessNames.remove(name, uid);
6445 }
6446 }
6447
Riddle Hsua0536432019-02-16 00:38:59 +08006448 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006449 @Override
6450 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006451 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006452 if (proc == mHomeProcess) {
6453 mHomeProcess = null;
6454 }
6455 if (proc == mPreviousProcess) {
6456 mPreviousProcess = null;
6457 }
6458 }
6459 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006460
Riddle Hsua0536432019-02-16 00:38:59 +08006461 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006462 @Override
6463 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006464 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006465 return mTopProcessState;
6466 }
6467 }
6468
Riddle Hsua0536432019-02-16 00:38:59 +08006469 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006470 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006471 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006472 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006473 return proc == mHeavyWeightProcess;
6474 }
6475 }
6476
Riddle Hsua0536432019-02-16 00:38:59 +08006477 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006478 @Override
6479 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006480 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006481 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6482 }
6483 }
6484
6485 @Override
6486 public void finishHeavyWeightApp() {
6487 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006488 if (mHeavyWeightProcess != null) {
6489 mHeavyWeightProcess.finishActivities();
6490 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006491 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6492 mHeavyWeightProcess);
6493 }
6494 }
6495
Riddle Hsua0536432019-02-16 00:38:59 +08006496 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006497 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006498 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006499 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006500 return isSleepingLocked();
6501 }
6502 }
6503
6504 @Override
6505 public boolean isShuttingDown() {
6506 synchronized (mGlobalLock) {
6507 return mShuttingDown;
6508 }
6509 }
6510
6511 @Override
6512 public boolean shuttingDown(boolean booted, int timeout) {
6513 synchronized (mGlobalLock) {
6514 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006515 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006516 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006517 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006518 return mStackSupervisor.shutdownLocked(timeout);
6519 }
6520 }
6521
6522 @Override
6523 public void enableScreenAfterBoot(boolean booted) {
6524 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006525 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006526 mWindowManager.enableScreenAfterBoot();
6527 updateEventDispatchingLocked(booted);
6528 }
6529 }
6530
6531 @Override
6532 public boolean showStrictModeViolationDialog() {
6533 synchronized (mGlobalLock) {
6534 return mShowDialogs && !mSleeping && !mShuttingDown;
6535 }
6536 }
6537
6538 @Override
6539 public void showSystemReadyErrorDialogsIfNeeded() {
6540 synchronized (mGlobalLock) {
6541 try {
6542 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6543 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6544 + " data partition or your device will be unstable.");
6545 mUiHandler.post(() -> {
6546 if (mShowDialogs) {
6547 AlertDialog d = new BaseErrorDialog(mUiContext);
6548 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6549 d.setCancelable(false);
6550 d.setTitle(mUiContext.getText(R.string.android_system_label));
6551 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6552 d.setButton(DialogInterface.BUTTON_POSITIVE,
6553 mUiContext.getText(R.string.ok),
6554 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6555 d.show();
6556 }
6557 });
6558 }
6559 } catch (RemoteException e) {
6560 }
6561
6562 if (!Build.isBuildConsistent()) {
6563 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6564 mUiHandler.post(() -> {
6565 if (mShowDialogs) {
6566 AlertDialog d = new BaseErrorDialog(mUiContext);
6567 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6568 d.setCancelable(false);
6569 d.setTitle(mUiContext.getText(R.string.android_system_label));
6570 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6571 d.setButton(DialogInterface.BUTTON_POSITIVE,
6572 mUiContext.getText(R.string.ok),
6573 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6574 d.show();
6575 }
6576 });
6577 }
6578 }
6579 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006580
6581 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006582 public void onProcessMapped(int pid, WindowProcessController proc) {
6583 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006584 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006585 }
6586 }
6587
6588 @Override
6589 public void onProcessUnMapped(int pid) {
6590 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006591 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006592 }
6593 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006594
6595 @Override
6596 public void onPackageDataCleared(String name) {
6597 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006598 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006599 mAppWarnings.onPackageDataCleared(name);
6600 }
6601 }
6602
6603 @Override
6604 public void onPackageUninstalled(String name) {
6605 synchronized (mGlobalLock) {
6606 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006607 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006608 }
6609 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006610
6611 @Override
6612 public void onPackageAdded(String name, boolean replacing) {
6613 synchronized (mGlobalLock) {
6614 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6615 }
6616 }
6617
6618 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006619 public void onPackageReplaced(ApplicationInfo aInfo) {
6620 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006621 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006622 }
6623 }
6624
6625 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006626 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6627 synchronized (mGlobalLock) {
6628 return compatibilityInfoForPackageLocked(ai);
6629 }
6630 }
6631
Yunfan Chen75157d72018-07-27 14:47:21 +09006632 /**
6633 * Set the corresponding display information for the process global configuration. To be
6634 * called when we need to show IME on a different display.
6635 *
6636 * @param pid The process id associated with the IME window.
6637 * @param displayId The ID of the display showing the IME.
6638 */
6639 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006640 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006641 // Don't update process-level configuration for Multi-Client IME process since other
6642 // IMEs on other displays will also receive this configuration change due to IME
6643 // services use the same application config/context.
6644 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006645
Yunfan Chen75157d72018-07-27 14:47:21 +09006646 if (pid == MY_PID || pid < 0) {
6647 if (DEBUG_CONFIGURATION) {
6648 Slog.w(TAG,
6649 "Trying to update display configuration for system/invalid process.");
6650 }
6651 return;
6652 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006653 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006654 final DisplayContent displayContent =
6655 mRootActivityContainer.getDisplayContent(displayId);
6656 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006657 // Call might come when display is not yet added or has been removed.
6658 if (DEBUG_CONFIGURATION) {
6659 Slog.w(TAG, "Trying to update display configuration for non-existing "
6660 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006661 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006662 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006663 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006664 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006665 if (process == null) {
6666 if (DEBUG_CONFIGURATION) {
6667 Slog.w(TAG, "Trying to update display configuration for invalid "
6668 + "process, pid=" + pid);
6669 }
6670 return;
6671 }
lumarkddc77fb2019-06-27 22:22:23 +08006672 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006673 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006674 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006675 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006676
6677 @Override
6678 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006679 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006680 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006681 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6682 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006683 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006684 }
6685 }
6686 }
6687
6688 @Override
6689 public void clearPendingResultForActivity(IBinder activityToken,
6690 WeakReference<PendingIntentRecord> pir) {
6691 synchronized (mGlobalLock) {
6692 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6693 if (r != null && r.pendingResults != null) {
6694 r.pendingResults.remove(pir);
6695 }
6696 }
6697 }
6698
6699 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006700 public ActivityTokens getTopActivityForTask(int taskId) {
6701 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08006702 final Task task = mRootActivityContainer.anyTaskForId(taskId);
6703 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006704 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6705 + " Requested task not found");
6706 return null;
6707 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006708 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006709 if (activity == null) {
6710 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6711 + " Requested activity not found");
6712 return null;
6713 }
6714 if (!activity.attachedToProcess()) {
6715 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6716 + activity);
6717 return null;
6718 }
6719 return new ActivityTokens(activity.appToken, activity.assistToken,
6720 activity.app.getThread());
6721 }
6722 }
6723
6724 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006725 public IIntentSender getIntentSender(int type, String packageName,
6726 int callingUid, int userId, IBinder token, String resultWho,
6727 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6728 Bundle bOptions) {
6729 synchronized (mGlobalLock) {
6730 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6731 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6732 }
6733 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006734
6735 @Override
6736 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6737 synchronized (mGlobalLock) {
6738 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6739 if (r == null) {
6740 return null;
6741 }
6742 if (r.mServiceConnectionsHolder == null) {
6743 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6744 ActivityTaskManagerService.this, r);
6745 }
6746
6747 return r.mServiceConnectionsHolder;
6748 }
6749 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006750
6751 @Override
6752 public Intent getHomeIntent() {
6753 synchronized (mGlobalLock) {
6754 return ActivityTaskManagerService.this.getHomeIntent();
6755 }
6756 }
6757
6758 @Override
6759 public boolean startHomeActivity(int userId, String reason) {
6760 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006761 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006762 }
6763 }
6764
6765 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006766 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006767 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006768 synchronized (mGlobalLock) {
6769 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006770 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006771 }
Chilun8b1f1be2019-03-13 17:14:36 +08006772 }
6773
6774 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006775 public boolean startHomeOnAllDisplays(int userId, String reason) {
6776 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006777 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006778 }
6779 }
6780
Riddle Hsua0536432019-02-16 00:38:59 +08006781 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006782 @Override
6783 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006784 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006785 if (mFactoryTest == FACTORY_TEST_OFF) {
6786 return false;
6787 }
6788 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6789 && wpc.mName.equals(mTopComponent.getPackageName())) {
6790 return true;
6791 }
6792 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6793 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6794 }
6795 }
6796
6797 @Override
6798 public void updateTopComponentForFactoryTest() {
6799 synchronized (mGlobalLock) {
6800 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6801 return;
6802 }
6803 final ResolveInfo ri = mContext.getPackageManager()
6804 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6805 final CharSequence errorMsg;
6806 if (ri != null) {
6807 final ActivityInfo ai = ri.activityInfo;
6808 final ApplicationInfo app = ai.applicationInfo;
6809 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6810 mTopAction = Intent.ACTION_FACTORY_TEST;
6811 mTopData = null;
6812 mTopComponent = new ComponentName(app.packageName, ai.name);
6813 errorMsg = null;
6814 } else {
6815 errorMsg = mContext.getResources().getText(
6816 com.android.internal.R.string.factorytest_not_system);
6817 }
6818 } else {
6819 errorMsg = mContext.getResources().getText(
6820 com.android.internal.R.string.factorytest_no_action);
6821 }
6822 if (errorMsg == null) {
6823 return;
6824 }
6825
6826 mTopAction = null;
6827 mTopData = null;
6828 mTopComponent = null;
6829 mUiHandler.post(() -> {
6830 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6831 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006832 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006833 });
6834 }
6835 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006836
Riddle Hsua0536432019-02-16 00:38:59 +08006837 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 @Override
6839 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6840 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006841 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006843 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006844
6845 wpc.clearRecentTasks();
6846 wpc.clearActivities();
6847
6848 if (wpc.isInstrumenting()) {
6849 finishInstrumentationCallback.run();
6850 }
6851
Jorim Jaggid0752812018-10-16 16:07:20 +02006852 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006853 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006854 try {
6855 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6856 // If there was nothing to resume, and we are not already restarting
6857 // this process, but there is a visible activity that is hosted by the
6858 // process...then make sure all visible activities are running, taking
6859 // care of restarting this process.
6860 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6861 !PRESERVE_WINDOWS);
6862 }
6863 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006864 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006865 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 }
6867 }
6868 }
6869
6870 @Override
6871 public void closeSystemDialogs(String reason) {
6872 enforceNotIsolatedCaller("closeSystemDialogs");
6873
6874 final int pid = Binder.getCallingPid();
6875 final int uid = Binder.getCallingUid();
6876 final long origId = Binder.clearCallingIdentity();
6877 try {
6878 synchronized (mGlobalLock) {
6879 // Only allow this from foreground processes, so that background
6880 // applications can't abuse it to prevent system UI from being shown.
6881 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006882 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006883 if (!proc.isPerceptible()) {
6884 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6885 + " from background process " + proc);
6886 return;
6887 }
6888 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 mWindowManager.closeSystemDialogs(reason);
6890
Wale Ogunwaled32da472018-11-16 07:19:28 -08006891 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006893 // Call into AM outside the synchronized block.
6894 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 } finally {
6896 Binder.restoreCallingIdentity(origId);
6897 }
6898 }
6899
6900 @Override
6901 public void cleanupDisabledPackageComponents(
6902 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6903 synchronized (mGlobalLock) {
6904 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006905 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006907 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 mStackSupervisor.scheduleIdleLocked();
6909 }
6910
6911 // Clean-up disabled tasks
6912 getRecentTasks().cleanupDisabledPackageTasksLocked(
6913 packageName, disabledClasses, userId);
6914 }
6915 }
6916
6917 @Override
6918 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6919 int userId) {
6920 synchronized (mGlobalLock) {
6921
6922 boolean didSomething =
6923 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006924 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006925 null, doit, evenPersistent, userId);
6926 return didSomething;
6927 }
6928 }
6929
6930 @Override
6931 public void resumeTopActivities(boolean scheduleIdle) {
6932 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006933 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 if (scheduleIdle) {
6935 mStackSupervisor.scheduleIdleLocked();
6936 }
6937 }
6938 }
6939
Riddle Hsua0536432019-02-16 00:38:59 +08006940 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006941 @Override
6942 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006943 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6945 }
6946 }
6947
Riddle Hsua0536432019-02-16 00:38:59 +08006948 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006949 @Override
6950 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006951 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006952 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6953 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6954 }
6955 try {
6956 return mRootActivityContainer.attachApplication(wpc);
6957 } finally {
6958 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6959 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006960 }
6961 }
6962
6963 @Override
6964 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6965 try {
6966 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6967 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6968 }
6969 } catch (RemoteException ex) {
6970 throw new SecurityException("Fail to check is caller a privileged app", ex);
6971 }
6972
6973 synchronized (mGlobalLock) {
6974 final long ident = Binder.clearCallingIdentity();
6975 try {
6976 if (mAmInternal.shouldConfirmCredentials(userId)) {
6977 if (mKeyguardController.isKeyguardLocked()) {
6978 // Showing launcher to avoid user entering credential twice.
6979 startHomeActivity(currentUserId, "notifyLockedProfile");
6980 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006981 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006982 }
6983 } finally {
6984 Binder.restoreCallingIdentity(ident);
6985 }
6986 }
6987 }
6988
6989 @Override
6990 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6991 mAmInternal.enforceCallingPermission(
6992 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6993
6994 synchronized (mGlobalLock) {
6995 final long ident = Binder.clearCallingIdentity();
6996 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006997 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6998 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006999 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007000 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7001 UserHandle.CURRENT);
7002 } finally {
7003 Binder.restoreCallingIdentity(ident);
7004 }
7005 }
7006 }
7007
7008 @Override
7009 public void writeActivitiesToProto(ProtoOutputStream proto) {
7010 synchronized (mGlobalLock) {
7011 // The output proto of "activity --proto activities"
7012 // is ActivityManagerServiceDumpActivitiesProto
Jeffrey Huangcb782852019-12-05 11:28:11 -08007013 mRootActivityContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007014 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7015 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007016 }
7017 }
7018
7019 @Override
7020 public void saveANRState(String reason) {
7021 synchronized (mGlobalLock) {
7022 final StringWriter sw = new StringWriter();
7023 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7024 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7025 if (reason != null) {
7026 pw.println(" Reason: " + reason);
7027 }
7028 pw.println();
7029 getActivityStartController().dump(pw, " ", null);
7030 pw.println();
7031 pw.println("-------------------------------------------------------------------------------");
7032 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7033 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7034 "" /* header */);
7035 pw.println();
7036 pw.close();
7037
7038 mLastANRState = sw.toString();
7039 }
7040 }
7041
7042 @Override
7043 public void clearSavedANRState() {
7044 synchronized (mGlobalLock) {
7045 mLastANRState = null;
7046 }
7047 }
7048
7049 @Override
7050 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7051 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7052 synchronized (mGlobalLock) {
7053 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7054 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7055 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7056 dumpLastANRLocked(pw);
7057 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7058 dumpLastANRTracesLocked(pw);
7059 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7060 dumpActivityStarterLocked(pw, dumpPackage);
7061 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7062 dumpActivityContainersLocked(pw);
7063 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7064 if (getRecentTasks() != null) {
7065 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7066 }
7067 }
7068 }
7069 }
7070
7071 @Override
7072 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7073 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7074 int wakefulness) {
7075 synchronized (mGlobalLock) {
7076 if (mHomeProcess != null && (dumpPackage == null
7077 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7078 if (needSep) {
7079 pw.println();
7080 needSep = false;
7081 }
7082 pw.println(" mHomeProcess: " + mHomeProcess);
7083 }
7084 if (mPreviousProcess != null && (dumpPackage == null
7085 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7086 if (needSep) {
7087 pw.println();
7088 needSep = false;
7089 }
7090 pw.println(" mPreviousProcess: " + mPreviousProcess);
7091 }
7092 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7093 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7094 StringBuilder sb = new StringBuilder(128);
7095 sb.append(" mPreviousProcessVisibleTime: ");
7096 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7097 pw.println(sb);
7098 }
7099 if (mHeavyWeightProcess != null && (dumpPackage == null
7100 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7101 if (needSep) {
7102 pw.println();
7103 needSep = false;
7104 }
7105 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7106 }
7107 if (dumpPackage == null) {
7108 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007109 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 }
7111 if (dumpAll) {
7112 if (dumpPackage == null) {
7113 pw.println(" mConfigWillChange: "
7114 + getTopDisplayFocusedStack().mConfigWillChange);
7115 }
7116 if (mCompatModePackages.getPackages().size() > 0) {
7117 boolean printed = false;
7118 for (Map.Entry<String, Integer> entry
7119 : mCompatModePackages.getPackages().entrySet()) {
7120 String pkg = entry.getKey();
7121 int mode = entry.getValue();
7122 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7123 continue;
7124 }
7125 if (!printed) {
7126 pw.println(" mScreenCompatPackages:");
7127 printed = true;
7128 }
7129 pw.println(" " + pkg + ": " + mode);
7130 }
7131 }
7132 }
7133
7134 if (dumpPackage == null) {
7135 pw.println(" mWakefulness="
7136 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007137 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007138 if (mRunningVoice != null) {
7139 pw.println(" mRunningVoice=" + mRunningVoice);
7140 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7141 }
7142 pw.println(" mSleeping=" + mSleeping);
7143 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7144 pw.println(" mVrController=" + mVrController);
7145 }
7146 if (mCurAppTimeTracker != null) {
7147 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7148 }
7149 if (mAllowAppSwitchUids.size() > 0) {
7150 boolean printed = false;
7151 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7152 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7153 for (int j = 0; j < types.size(); j++) {
7154 if (dumpPackage == null ||
7155 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7156 if (needSep) {
7157 pw.println();
7158 needSep = false;
7159 }
7160 if (!printed) {
7161 pw.println(" mAllowAppSwitchUids:");
7162 printed = true;
7163 }
7164 pw.print(" User ");
7165 pw.print(mAllowAppSwitchUids.keyAt(i));
7166 pw.print(": Type ");
7167 pw.print(types.keyAt(j));
7168 pw.print(" = ");
7169 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7170 pw.println();
7171 }
7172 }
7173 }
7174 }
7175 if (dumpPackage == null) {
7176 if (mController != null) {
7177 pw.println(" mController=" + mController
7178 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7179 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007180 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7181 pw.println(" mLaunchingActivityWakeLock="
7182 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184
7185 return needSep;
7186 }
7187 }
7188
7189 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007190 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7191 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007192 synchronized (mGlobalLock) {
7193 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007194 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007195 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007196 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7197 if (mRunningVoice != null) {
7198 final long vrToken = proto.start(
7199 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7200 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7201 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007202 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007203 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7204 proto.end(vrToken);
7205 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007206 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007207 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007208 if (mController != null) {
7209 final long token = proto.start(CONTROLLER);
7210 proto.write(CONTROLLER, mController.toString());
7211 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7212 proto.end(token);
7213 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007214 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7215 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007216 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 }
7218
7219 if (mHomeProcess != null && (dumpPackage == null
7220 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007221 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 }
7223
7224 if (mPreviousProcess != null && (dumpPackage == null
7225 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007226 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007227 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7228 }
7229
7230 if (mHeavyWeightProcess != null && (dumpPackage == null
7231 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007232 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007233 }
7234
7235 for (Map.Entry<String, Integer> entry
7236 : mCompatModePackages.getPackages().entrySet()) {
7237 String pkg = entry.getKey();
7238 int mode = entry.getValue();
7239 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7240 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7241 proto.write(PACKAGE, pkg);
7242 proto.write(MODE, mode);
7243 proto.end(compatToken);
7244 }
7245 }
7246
7247 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007248 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007249 }
7250
7251 }
7252 }
7253
7254 @Override
7255 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7256 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7257 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007258 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7259 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007260 }
7261
7262 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007263 public void dumpForOom(PrintWriter pw) {
7264 synchronized (mGlobalLock) {
7265 pw.println(" mHomeProcess: " + mHomeProcess);
7266 pw.println(" mPreviousProcess: " + mPreviousProcess);
7267 if (mHeavyWeightProcess != null) {
7268 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7269 }
7270 }
7271 }
7272
7273 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007274 public boolean canGcNow() {
7275 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007276 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007277 }
7278 }
7279
Riddle Hsua0536432019-02-16 00:38:59 +08007280 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007281 @Override
7282 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007283 synchronized (mGlobalLockWithoutBoost) {
Louis Chang3ff72a82019-12-17 12:12:59 +08007284 if (mRootActivityContainer == null) {
7285 // Return null if mRootActivityContainer not yet initialize, while update
7286 // oomadj after AMS created.
7287 return null;
7288 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08007289 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007290 return top != null ? top.app : null;
7291 }
7292 }
7293
Riddle Hsua0536432019-02-16 00:38:59 +08007294 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007295 @Override
7296 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007297 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007298 if (mRootActivityContainer != null) {
7299 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007300 }
7301 }
7302 }
7303
7304 @Override
7305 public void scheduleDestroyAllActivities(String reason) {
7306 synchronized (mGlobalLock) {
Wale Ogunwale196db712019-12-27 15:35:39 +00007307 mRootActivityContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007308 }
7309 }
7310
7311 @Override
7312 public void removeUser(int userId) {
7313 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007314 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007315 }
7316 }
7317
7318 @Override
7319 public boolean switchUser(int userId, UserState userState) {
7320 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007321 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007322 }
7323 }
7324
7325 @Override
7326 public void onHandleAppCrash(WindowProcessController wpc) {
7327 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007328 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007329 }
7330 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007331
7332 @Override
7333 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7334 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007335 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007336 }
7337 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007338
Riddle Hsua0536432019-02-16 00:38:59 +08007339 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007340 @Override
7341 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007342 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007343 }
7344
Riddle Hsua0536432019-02-16 00:38:59 +08007345 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007346 @Override
7347 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007348 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007349 }
7350
Riddle Hsua0536432019-02-16 00:38:59 +08007351 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007352 @Override
7353 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007354 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007355 }
7356
Riddle Hsua0536432019-02-16 00:38:59 +08007357 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007358 @Override
7359 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007360 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007361 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007362
7363 @Override
7364 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007365 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007366 mPendingTempWhitelist.put(uid, tag);
7367 }
7368 }
7369
7370 @Override
7371 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007372 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007373 mPendingTempWhitelist.remove(uid);
7374 }
7375 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007376
7377 @Override
7378 public boolean handleAppCrashInActivityController(String processName, int pid,
7379 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7380 Runnable killCrashingAppCallback) {
7381 synchronized (mGlobalLock) {
7382 if (mController == null) {
7383 return false;
7384 }
7385
7386 try {
7387 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7388 stackTrace)) {
7389 killCrashingAppCallback.run();
7390 return true;
7391 }
7392 } catch (RemoteException e) {
7393 mController = null;
7394 Watchdog.getInstance().setActivityController(null);
7395 }
7396 return false;
7397 }
7398 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007399
7400 @Override
7401 public void removeRecentTasksByPackageName(String packageName, int userId) {
7402 synchronized (mGlobalLock) {
7403 mRecentTasks.removeTasksByPackageName(packageName, userId);
7404 }
7405 }
7406
7407 @Override
7408 public void cleanupRecentTasksForUser(int userId) {
7409 synchronized (mGlobalLock) {
7410 mRecentTasks.cleanupLocked(userId);
7411 }
7412 }
7413
7414 @Override
7415 public void loadRecentTasksForUser(int userId) {
7416 synchronized (mGlobalLock) {
7417 mRecentTasks.loadUserRecentsLocked(userId);
7418 }
7419 }
7420
7421 @Override
7422 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7423 synchronized (mGlobalLock) {
7424 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7425 }
7426 }
7427
7428 @Override
7429 public void flushRecentTasks() {
7430 mRecentTasks.flush();
7431 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007432
7433 @Override
7434 public WindowProcessController getHomeProcess() {
7435 synchronized (mGlobalLock) {
7436 return mHomeProcess;
7437 }
7438 }
7439
7440 @Override
7441 public WindowProcessController getPreviousProcess() {
7442 synchronized (mGlobalLock) {
7443 return mPreviousProcess;
7444 }
7445 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007446
7447 @Override
7448 public void clearLockedTasks(String reason) {
7449 synchronized (mGlobalLock) {
7450 getLockTaskController().clearLockedTasks(reason);
7451 }
7452 }
7453
7454 @Override
7455 public void updateUserConfiguration() {
7456 synchronized (mGlobalLock) {
7457 final Configuration configuration = new Configuration(getGlobalConfiguration());
7458 final int currentUserId = mAmInternal.getCurrentUserId();
7459 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7460 configuration, currentUserId, Settings.System.canWrite(mContext));
7461 updateConfigurationLocked(configuration, null /* starting */,
7462 false /* initLocale */, false /* persistent */, currentUserId,
7463 false /* deferResume */);
7464 }
7465 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007466
7467 @Override
7468 public boolean canShowErrorDialogs() {
7469 synchronized (mGlobalLock) {
7470 return mShowDialogs && !mSleeping && !mShuttingDown
7471 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7472 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7473 mAmInternal.getCurrentUserId())
7474 && !(UserManager.isDeviceInDemoMode(mContext)
7475 && mAmInternal.getCurrentUser().isDemo());
7476 }
7477 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007478
7479 @Override
7480 public void setProfileApp(String profileApp) {
7481 synchronized (mGlobalLock) {
7482 mProfileApp = profileApp;
7483 }
7484 }
7485
7486 @Override
7487 public void setProfileProc(WindowProcessController wpc) {
7488 synchronized (mGlobalLock) {
7489 mProfileProc = wpc;
7490 }
7491 }
7492
7493 @Override
7494 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7495 synchronized (mGlobalLock) {
7496 mProfilerInfo = profilerInfo;
7497 }
7498 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007499
7500 @Override
7501 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7502 synchronized (mGlobalLock) {
7503 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7504 }
7505 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007506
7507 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007508 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7509 boolean reducedResolution) {
7510 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7511 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007512 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007513
7514 @Override
7515 public boolean isUidForeground(int uid) {
7516 synchronized (mGlobalLock) {
7517 return ActivityTaskManagerService.this.isUidForeground(uid);
7518 }
7519 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007520
7521 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007522 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007523 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007524 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007525 }
7526 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007527
7528 @Override
7529 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007530 // Translate package names into UIDs
7531 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007532 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007533 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7534 if (uid >= 0) {
7535 result.add(uid);
7536 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007537 }
7538 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007539 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007540 }
7541 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007542 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007543}