blob: 40a45641ab04fc819a142fe53c53e8ce07222cf3 [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;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
214import android.service.voice.IVoiceInteractionSession;
215import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900216import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.telecom.TelecomManager;
218import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100219import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700221import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700223import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
Robert Carr8a2f9132019-11-11 15:03:15 -0800229import android.view.ITaskOrganizer;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700232import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700236import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700238import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700240import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700243import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
244import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700246import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.internal.policy.IKeyguardDismissCallback;
248import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700249import com.android.internal.util.ArrayUtils;
250import com.android.internal.util.FastPrintWriter;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
261import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900268import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700295import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000299import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700300import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
302/**
303 * System service for managing activities and their containers (task, stacks, displays,... ).
304 *
305 * {@hide}
306 */
307public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800309 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000310 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700311 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
312 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
313 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
314 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700315 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700316
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700318 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700319 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700320 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100321 // How long we permit background activity starts after an activity in the process
322 // started or finished.
323 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700324
Wale Ogunwale98875612018-10-12 07:53:02 -0700325 /** Used to indicate that an app transition should be animated. */
326 static final boolean ANIMATE = true;
327
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700328 /** Hardware-reported OpenGLES version. */
329 final int GL_ES_VERSION;
330
Wale Ogunwale31913b52018-10-13 08:29:31 -0700331 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
332 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
333 public static final String DUMP_LASTANR_CMD = "lastanr" ;
334 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
335 public static final String DUMP_STARTER_CMD = "starter" ;
336 public static final String DUMP_CONTAINERS_CMD = "containers" ;
337 public static final String DUMP_RECENTS_CMD = "recents" ;
338 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
339
Wale Ogunwale64258362018-10-16 15:13:37 -0700340 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
341 public static final int RELAUNCH_REASON_NONE = 0;
342 /** This activity is being relaunched due to windowing mode change. */
343 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
344 /** This activity is being relaunched due to a free-resize operation. */
345 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
346
Evan Rosky226de132020-01-03 18:00:29 -0800347 /** Flag indicating that an applied transaction may have effected lifecycle */
348 private static final int TRANSACT_EFFECTS_CLIENT_CONFIG = 1;
349 private static final int TRANSACT_EFFECTS_LIFECYCLE = 1 << 1;
350
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700351 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700352
Wale Ogunwalef6733932018-06-27 05:14:34 -0700353 /**
354 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
355 * change at runtime. Use mContext for non-UI purposes.
356 */
357 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700358 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700359 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700360 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700361 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700362 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700363 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800364 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800365 @VisibleForTesting
366 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700367 PowerManagerInternal mPowerManagerInternal;
368 private UsageStatsManagerInternal mUsageStatsInternal;
369
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700370 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700371 IntentFirewall mIntentFirewall;
372
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700373 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800374 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800375 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700376 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800377 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
378 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
379 *
380 * @see WindowManagerThreadPriorityBooster
381 */
382 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700383 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800384 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700385 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700386 private UserManagerService mUserManager;
387 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700388 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800389 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700390 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700391 /** All processes currently running that might have a window organized by name. */
392 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100393 /** All processes we currently have running mapped by pid and uid */
394 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700395 /** This is the process holding what we currently consider to be the "home" activity. */
396 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700397 /** The currently running heavy-weight process, if any. */
398 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700399 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700400 /**
401 * This is the process holding the activity the user last visited that is in a different process
402 * from the one they are currently in.
403 */
404 WindowProcessController mPreviousProcess;
405 /** The time at which the previous process was last visible. */
406 long mPreviousProcessVisibleTime;
407
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700408 /** List of intents that were used to start the most recent tasks. */
409 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700410 /** State of external calls telling us if the device is awake or asleep. */
411 private boolean mKeyguardShown = false;
412
413 // Wrapper around VoiceInteractionServiceManager
414 private AssistUtils mAssistUtils;
415
416 // VoiceInteraction session ID that changes for each new request except when
417 // being called for multi-window assist in a single session.
418 private int mViSessionId = 1000;
419
420 // How long to wait in getAssistContextExtras for the activity and foreground services
421 // to respond with the result.
422 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
423
424 // How long top wait when going through the modern assist (which doesn't need to block
425 // on getting this result before starting to launch its UI).
426 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
427
428 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
429 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
430
Alison Cichowlas3e340502018-08-07 17:15:01 -0400431 // Permission tokens are used to temporarily granted a trusted app the ability to call
432 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
433 // showing any appropriate error messages to the user.
434 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
435 10 * MINUTE_IN_MILLIS;
436
437 // How long before the service actually expires a token. This is slightly longer than
438 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
439 // expiration exception.
440 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
441 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
442
443 // How long the service will remember expired tokens, for the purpose of providing error
444 // messaging when a client uses an expired token.
445 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
446 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
447
448 // Activity tokens of system activities that are delegating their call to
449 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
450 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
451
452 // Permission tokens that have expired, but we remember for error reporting.
453 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
454
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700455 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
456
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700457 // Keeps track of the active voice interaction service component, notified from
458 // VoiceInteractionManagerService
459 ComponentName mActiveVoiceInteractionServiceComponent;
460
Michal Karpinskida34cd42019-04-02 19:46:52 +0100461 // A map userId and all its companion app uids
462 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000463
Wale Ogunwalee2172292018-10-25 10:11:10 -0700464 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700465 KeyguardController mKeyguardController;
466 private final ClientLifecycleManager mLifecycleManager;
467 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700468 /** The controller for all operations related to locktask. */
469 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700470 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700471
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700472 boolean mSuppressResizeConfigChanges;
473
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700474 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700475 new UpdateConfigurationResult();
476
477 static final class UpdateConfigurationResult {
478 // Configuration changes that were updated.
479 int changes;
480 // If the activity was relaunched to match the new configuration.
481 boolean activityRelaunched;
482
483 void reset() {
484 changes = 0;
485 activityRelaunched = false;
486 }
487 }
488
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700489 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700490 private int mConfigurationSeq;
491 // To cache the list of supported system locales
492 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700493
494 /**
495 * Temp object used when global and/or display override configuration is updated. It is also
496 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
497 * anyone...
498 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 private Configuration mTempConfig = new Configuration();
500
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 /** Temporary to avoid allocations. */
502 final StringBuilder mStringBuilder = new StringBuilder(256);
503
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700504 // Amount of time after a call to stopAppSwitches() during which we will
505 // prevent further untrusted switches from happening.
506 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
507
508 /**
509 * The time at which we will allow normal application switches again,
510 * after a call to {@link #stopAppSwitches()}.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 /**
514 * This is set to true after the first switch after mAppSwitchesAllowedTime
515 * is set; any switches after that will clear the time.
516 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700517 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518
Ricky Wai906af482019-06-03 17:25:28 +0100519 /**
520 * Last stop app switches time, apps finished before this time cannot start background activity
521 * even if they are in grace period.
522 */
523 private long mLastStopAppSwitchesTime;
524
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700525 IActivityController mController = null;
526 boolean mControllerIsAMonkey = false;
527
Wale Ogunwale214f3482018-10-04 11:00:47 -0700528 final int mFactoryTest;
529
530 /** Used to control how we initialize the service. */
531 ComponentName mTopComponent;
532 String mTopAction = Intent.ACTION_MAIN;
533 String mTopData;
534
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800535 /** Profiling app information. */
536 String mProfileApp = null;
537 WindowProcessController mProfileProc = null;
538 ProfilerInfo mProfilerInfo = null;
539
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700541 * Dump of the activity state at the time of the last ANR. Cleared after
542 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
543 */
544 String mLastANRState;
545
546 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700547 * Used to retain an update lock when the foreground activity is in
548 * immersive mode.
549 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700551
552 /**
553 * Packages that are being allowed to perform unrestricted app switches. Mapping is
554 * User -> Type -> uid.
555 */
556 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
557
558 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700559 private int mThumbnailWidth;
560 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700561
562 /**
563 * Flag that indicates if multi-window is enabled.
564 *
565 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
566 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
567 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
568 * At least one of the forms of multi-window must be enabled in order for this flag to be
569 * initialized to 'true'.
570 *
571 * @see #mSupportsSplitScreenMultiWindow
572 * @see #mSupportsFreeformWindowManagement
573 * @see #mSupportsPictureInPicture
574 * @see #mSupportsMultiDisplay
575 */
576 boolean mSupportsMultiWindow;
577 boolean mSupportsSplitScreenMultiWindow;
578 boolean mSupportsFreeformWindowManagement;
579 boolean mSupportsPictureInPicture;
580 boolean mSupportsMultiDisplay;
581 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700582 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700583
584 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
585
586 // VR Vr2d Display Id.
587 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700588
Wale Ogunwalef6733932018-06-27 05:14:34 -0700589 /**
590 * Set while we are wanting to sleep, to prevent any
591 * activities from being started/resumed.
592 *
593 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
594 *
595 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
596 * while in the sleep state until there is a pending transition out of sleep, in which case
597 * mSleeping is set to false, and remains false while awake.
598 *
599 * Whether mSleeping can quickly toggled between true/false without the device actually
600 * display changing states is undefined.
601 */
602 private boolean mSleeping = false;
603
604 /**
605 * The process state used for processes that are running the top activities.
606 * This changes between TOP and TOP_SLEEPING to following mSleeping.
607 */
608 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
609
Riddle Hsua0022cd2019-09-09 21:12:41 +0800610 @Retention(RetentionPolicy.SOURCE)
611 @IntDef({
612 LAYOUT_REASON_CONFIG_CHANGED,
613 LAYOUT_REASON_VISIBILITY_CHANGED,
614 })
615 @interface LayoutReason {}
616 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
617 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
618
619 /** The reasons to perform surface placement. */
620 @LayoutReason
621 private int mLayoutReasons;
622
Wale Ogunwalef6733932018-06-27 05:14:34 -0700623 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
624 // automatically. Important for devices without direct input devices.
625 private boolean mShowDialogs = true;
626
627 /** Set if we are shutting down the system, similar to sleeping. */
628 boolean mShuttingDown = false;
629
630 /**
631 * We want to hold a wake lock while running a voice interaction session, since
632 * this may happen with the screen off and we need to keep the CPU running to
633 * be able to continue to interact with the user.
634 */
635 PowerManager.WakeLock mVoiceWakeLock;
636
637 /**
638 * Set while we are running a voice interaction. This overrides sleeping while it is active.
639 */
640 IVoiceInteractionSession mRunningVoice;
641
642 /**
643 * The last resumed activity. This is identical to the current resumed activity most
644 * of the time but could be different when we're pausing one activity before we resume
645 * another activity.
646 */
647 ActivityRecord mLastResumedActivity;
648
649 /**
650 * The activity that is currently being traced as the active resumed activity.
651 *
652 * @see #updateResumedAppTrace
653 */
654 private @Nullable ActivityRecord mTracedResumedActivity;
655
656 /** If non-null, we are tracking the time the user spends in the currently focused app. */
657 AppTimeTracker mCurAppTimeTracker;
658
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700659 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700660
Wale Ogunwale53783742018-09-16 10:21:51 -0700661 /**
662 * Packages that the user has asked to have run in screen size
663 * compatibility mode instead of filling the screen.
664 */
665 CompatModePackages mCompatModePackages;
666
Wale Ogunwalef6733932018-06-27 05:14:34 -0700667 private FontScaleSettingObserver mFontScaleSettingObserver;
668
Robert Carr8a2f9132019-11-11 15:03:15 -0800669 /**
670 * Stores the registration and state of TaskOrganizers in use.
671 */
672 TaskOrganizerController mTaskOrganizerController =
673 new TaskOrganizerController(this, mGlobalLock);
674
Ricky Wai96f5c352019-04-10 18:40:17 +0100675 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000676
Wale Ogunwalef6733932018-06-27 05:14:34 -0700677 private final class FontScaleSettingObserver extends ContentObserver {
678 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
679 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
680
681 public FontScaleSettingObserver() {
682 super(mH);
683 final ContentResolver resolver = mContext.getContentResolver();
684 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
685 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
686 UserHandle.USER_ALL);
687 }
688
689 @Override
690 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
691 if (mFontScaleUri.equals(uri)) {
692 updateFontScaleIfNeeded(userId);
693 } else if (mHideErrorDialogsUri.equals(uri)) {
694 synchronized (mGlobalLock) {
695 updateShouldShowDialogsLocked(getGlobalConfiguration());
696 }
697 }
698 }
699 }
700
Riddle Hsua0536432019-02-16 00:38:59 +0800701 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
702 @Target(ElementType.METHOD)
703 @Retention(RetentionPolicy.SOURCE)
704 @interface HotPath {
705 int NONE = 0;
706 int OOM_ADJUSTMENT = 1;
707 int LRU_UPDATE = 2;
708 int PROCESS_CHANGE = 3;
709 int caller() default NONE;
710 }
711
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800712 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
713 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900714 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800715 mAmInternal.updateOomAdj();
716 }
717 };
718
Charles Chen8d98dd22018-12-26 17:36:54 +0800719 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
720 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700721 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700722 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700723 mSystemThread = ActivityThread.currentActivityThread();
724 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700725 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800726 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700727 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onSystemReady() {
731 synchronized (mGlobalLock) {
732 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
733 PackageManager.FEATURE_CANT_SAVE_STATE);
734 mAssistUtils = new AssistUtils(mContext);
735 mVrController.onSystemReady();
736 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700737 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700739 }
740
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700741 public void onInitPowerManagement() {
742 synchronized (mGlobalLock) {
743 mStackSupervisor.initPowerManagement();
744 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
745 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
746 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
747 mVoiceWakeLock.setReferenceCounted(false);
748 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700749 }
750
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700751 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700752 mFontScaleSettingObserver = new FontScaleSettingObserver();
753 }
754
Wale Ogunwale59507092018-10-29 09:00:30 -0700755 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 final boolean freeformWindowManagement =
757 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
758 || Settings.Global.getInt(
759 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
760
761 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
762 final boolean supportsPictureInPicture = supportsMultiWindow &&
763 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
764 final boolean supportsSplitScreenMultiWindow =
765 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
766 final boolean supportsMultiDisplay = mContext.getPackageManager()
767 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
769 final boolean forceResizable = Settings.Global.getInt(
770 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700771 final boolean sizeCompatFreeform = Settings.Global.getInt(
772 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773
774 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900775 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776
777 final Configuration configuration = new Configuration();
778 Settings.System.getConfiguration(resolver, configuration);
779 if (forceRtl) {
780 // This will take care of setting the correct layout direction flags
781 configuration.setLayoutDirection(configuration.locale);
782 }
783
784 synchronized (mGlobalLock) {
785 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700786 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700787 final boolean multiWindowFormEnabled = freeformWindowManagement
788 || supportsSplitScreenMultiWindow
789 || supportsPictureInPicture
790 || supportsMultiDisplay;
791 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
792 mSupportsMultiWindow = true;
793 mSupportsFreeformWindowManagement = freeformWindowManagement;
794 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
795 mSupportsPictureInPicture = supportsPictureInPicture;
796 mSupportsMultiDisplay = supportsMultiDisplay;
797 } else {
798 mSupportsMultiWindow = false;
799 mSupportsFreeformWindowManagement = false;
800 mSupportsSplitScreenMultiWindow = false;
801 mSupportsPictureInPicture = false;
802 mSupportsMultiDisplay = false;
803 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700804 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700805 // This happens before any activities are started, so we can change global configuration
806 // in-place.
807 updateConfigurationLocked(configuration, null, true);
808 final Configuration globalConfig = getGlobalConfiguration();
809 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
810
811 // Load resources only after the current configuration has been set.
812 final Resources res = mContext.getResources();
813 mThumbnailWidth = res.getDimensionPixelSize(
814 com.android.internal.R.dimen.thumbnail_width);
815 mThumbnailHeight = res.getDimensionPixelSize(
816 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 }
818 }
819
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800820 public WindowManagerGlobalLock getGlobalLock() {
821 return mGlobalLock;
822 }
823
Yunfan Chen585f2932019-01-29 16:04:45 +0900824 /** For test purpose only. */
825 @VisibleForTesting
826 public ActivityTaskManagerInternal getAtmInternal() {
827 return mInternal;
828 }
829
Riddle Hsud93a6c42018-11-29 21:50:06 +0800830 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
831 Looper looper) {
832 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700833 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700834 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700835 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800836 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700837 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700838 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700839 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700842 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700843 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700844 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700845 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700846 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 mKeyguardController = mStackSupervisor.getKeyguardController();
848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void onActivityManagerInternalAdded() {
851 synchronized (mGlobalLock) {
852 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
853 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
854 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 int increaseConfigurationSeqLocked() {
858 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
859 return mConfigurationSeq;
860 }
861
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700862 protected ActivityStackSupervisor createStackSupervisor() {
863 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
864 supervisor.initialize();
865 return supervisor;
866 }
867
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800868 protected AppWarnings createAppWarnings(
869 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
870 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
871 }
872
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 public void setWindowManager(WindowManagerService wm) {
874 synchronized (mGlobalLock) {
875 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800876 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800877 mTempConfig.setToDefaults();
878 mTempConfig.setLocales(LocaleList.getDefault());
879 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800880 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700881 mLockTaskController.setWindowManager(wm);
882 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800883 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700884 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700885 }
886
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700887 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
888 synchronized (mGlobalLock) {
889 mUsageStatsInternal = usageStatsManager;
890 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700891 }
892
Wale Ogunwalef6733932018-06-27 05:14:34 -0700893 UserManagerService getUserManager() {
894 if (mUserManager == null) {
895 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
896 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
897 }
898 return mUserManager;
899 }
900
901 AppOpsService getAppOpsService() {
902 if (mAppOpsService == null) {
903 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
904 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
905 }
906 return mAppOpsService;
907 }
908
909 boolean hasUserRestriction(String restriction, int userId) {
910 return getUserManager().hasUserRestriction(restriction, userId);
911 }
912
Michal Karpinski15486842019-04-25 17:33:42 +0100913 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
914 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800915 callingUid, callingPackage, /* featureId */ null, false, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100916 if (mode == AppOpsManager.MODE_DEFAULT) {
917 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
918 == PERMISSION_GRANTED;
919 }
920 return mode == AppOpsManager.MODE_ALLOWED;
921 }
922
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700923 @VisibleForTesting
924 protected void setRecentTasks(RecentTasks recentTasks) {
925 mRecentTasks = recentTasks;
926 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700927 }
928
929 RecentTasks getRecentTasks() {
930 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700931 }
932
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700933 ClientLifecycleManager getLifecycleManager() {
934 return mLifecycleManager;
935 }
936
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700937 ActivityStartController getActivityStartController() {
938 return mActivityStartController;
939 }
940
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700941 TaskChangeNotificationController getTaskChangeNotificationController() {
942 return mTaskChangeNotificationController;
943 }
944
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700945 LockTaskController getLockTaskController() {
946 return mLockTaskController;
947 }
948
Yunfan Chen75157d72018-07-27 14:47:21 +0900949 /**
950 * Return the global configuration used by the process corresponding to the input pid. This is
951 * usually the global configuration with some overrides specific to that process.
952 */
953 Configuration getGlobalConfigurationForCallingPid() {
954 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800955 return getGlobalConfigurationForPid(pid);
956 }
957
958 /**
959 * Return the global configuration used by the process corresponding to the given pid.
960 */
961 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900962 if (pid == MY_PID || pid < 0) {
963 return getGlobalConfiguration();
964 }
965 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100966 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900967 return app != null ? app.getConfiguration() : getGlobalConfiguration();
968 }
969 }
970
971 /**
972 * Return the device configuration info used by the process corresponding to the input pid.
973 * The value is consistent with the global configuration for the process.
974 */
975 @Override
976 public ConfigurationInfo getDeviceConfigurationInfo() {
977 ConfigurationInfo config = new ConfigurationInfo();
978 synchronized (mGlobalLock) {
979 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
980 config.reqTouchScreen = globalConfig.touchscreen;
981 config.reqKeyboardType = globalConfig.keyboard;
982 config.reqNavigation = globalConfig.navigation;
983 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
984 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
985 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
986 }
987 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
988 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
989 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
990 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700991 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900992 }
993 return config;
994 }
995
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700996 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700997 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700998 }
999
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001000 public static final class Lifecycle extends SystemService {
1001 private final ActivityTaskManagerService mService;
1002
1003 public Lifecycle(Context context) {
1004 super(context);
1005 mService = new ActivityTaskManagerService(context);
1006 }
1007
1008 @Override
1009 public void onStart() {
1010 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001011 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001012 }
1013
Garfield Tan891146c2018-10-09 12:14:00 -07001014 @Override
1015 public void onUnlockUser(int userId) {
1016 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001017 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001018 }
1019 }
1020
1021 @Override
1022 public void onCleanupUser(int userId) {
1023 synchronized (mService.getGlobalLock()) {
1024 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1025 }
1026 }
1027
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001028 public ActivityTaskManagerService getService() {
1029 return mService;
1030 }
1031 }
1032
1033 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 public final int startActivity(IApplicationThread caller, String callingPackage,
1035 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1036 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1037 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1038 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1039 UserHandle.getCallingUserId());
1040 }
1041
1042 @Override
1043 public final int startActivities(IApplicationThread caller, String callingPackage,
1044 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1045 int userId) {
1046 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001047 enforceNotIsolatedCaller(reason);
1048 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001049 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001050 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1051 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1052 reason, null /* originatingPendingIntent */,
1053 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001054 }
1055
1056 @Override
1057 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1058 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1059 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1060 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1061 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1062 true /*validateIncomingUser*/);
1063 }
1064
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001065 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001066 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1067 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1068 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001069 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001070
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001071 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001072 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1073
1074 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001075 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 .setCaller(caller)
1077 .setCallingPackage(callingPackage)
1078 .setResolvedType(resolvedType)
1079 .setResultTo(resultTo)
1080 .setResultWho(resultWho)
1081 .setRequestCode(requestCode)
1082 .setStartFlags(startFlags)
1083 .setProfilerInfo(profilerInfo)
1084 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001085 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001086 .execute();
1087
1088 }
1089
1090 @Override
1091 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1092 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1094 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001095 // Refuse possible leaked file descriptors
1096 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1097 throw new IllegalArgumentException("File descriptors passed in Intent");
1098 }
1099
1100 if (!(target instanceof PendingIntentRecord)) {
1101 throw new IllegalArgumentException("Bad PendingIntent object");
1102 }
1103
1104 PendingIntentRecord pir = (PendingIntentRecord)target;
1105
1106 synchronized (mGlobalLock) {
1107 // If this is coming from the currently resumed activity, it is
1108 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001109 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001110 if (stack.mResumedActivity != null &&
1111 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001112 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 }
1114 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001115 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001116 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001117 }
1118
1119 @Override
1120 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1121 Bundle bOptions) {
1122 // Refuse possible leaked file descriptors
1123 if (intent != null && intent.hasFileDescriptors()) {
1124 throw new IllegalArgumentException("File descriptors passed in Intent");
1125 }
1126 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1127
1128 synchronized (mGlobalLock) {
1129 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1130 if (r == null) {
1131 SafeActivityOptions.abort(options);
1132 return false;
1133 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001134 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 // The caller is not running... d'oh!
1136 SafeActivityOptions.abort(options);
1137 return false;
1138 }
1139 intent = new Intent(intent);
1140 // The caller is not allowed to change the data.
1141 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1142 // And we are resetting to find the next component...
1143 intent.setComponent(null);
1144
1145 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1146
1147 ActivityInfo aInfo = null;
1148 try {
1149 List<ResolveInfo> resolves =
1150 AppGlobals.getPackageManager().queryIntentActivities(
1151 intent, r.resolvedType,
1152 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1153 UserHandle.getCallingUserId()).getList();
1154
1155 // Look for the original activity in the list...
1156 final int N = resolves != null ? resolves.size() : 0;
1157 for (int i=0; i<N; i++) {
1158 ResolveInfo rInfo = resolves.get(i);
1159 if (rInfo.activityInfo.packageName.equals(r.packageName)
1160 && rInfo.activityInfo.name.equals(r.info.name)) {
1161 // We found the current one... the next matching is
1162 // after it.
1163 i++;
1164 if (i<N) {
1165 aInfo = resolves.get(i).activityInfo;
1166 }
1167 if (debug) {
1168 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1169 + "/" + r.info.name);
1170 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1171 ? "null" : aInfo.packageName + "/" + aInfo.name));
1172 }
1173 break;
1174 }
1175 }
1176 } catch (RemoteException e) {
1177 }
1178
1179 if (aInfo == null) {
1180 // Nobody who is next!
1181 SafeActivityOptions.abort(options);
1182 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1183 return false;
1184 }
1185
1186 intent.setComponent(new ComponentName(
1187 aInfo.applicationInfo.packageName, aInfo.name));
1188 intent.setFlags(intent.getFlags()&~(
1189 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1190 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1191 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1192 FLAG_ACTIVITY_NEW_TASK));
1193
1194 // Okay now we need to start the new activity, replacing the currently running activity.
1195 // This is a little tricky because we want to start the new one as if the current one is
1196 // finished, but not finish the current one first so that there is no flicker.
1197 // And thus...
1198 final boolean wasFinishing = r.finishing;
1199 r.finishing = true;
1200
1201 // Propagate reply information over to the new activity.
1202 final ActivityRecord resultTo = r.resultTo;
1203 final String resultWho = r.resultWho;
1204 final int requestCode = r.requestCode;
1205 r.resultTo = null;
1206 if (resultTo != null) {
1207 resultTo.removeResultsLocked(r, resultWho, requestCode);
1208 }
1209
1210 final long origId = Binder.clearCallingIdentity();
1211 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001212 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001213 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001214 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001215 .setResolvedType(r.resolvedType)
1216 .setActivityInfo(aInfo)
1217 .setResultTo(resultTo != null ? resultTo.appToken : null)
1218 .setResultWho(resultWho)
1219 .setRequestCode(requestCode)
1220 .setCallingPid(-1)
1221 .setCallingUid(r.launchedFromUid)
1222 .setCallingPackage(r.launchedFromPackage)
1223 .setRealCallingPid(-1)
1224 .setRealCallingUid(r.launchedFromUid)
1225 .setActivityOptions(options)
1226 .execute();
1227 Binder.restoreCallingIdentity(origId);
1228
1229 r.finishing = wasFinishing;
1230 if (res != ActivityManager.START_SUCCESS) {
1231 return false;
1232 }
1233 return true;
1234 }
1235 }
1236
1237 @Override
1238 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1239 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1240 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1241 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001242 enforceNotIsolatedCaller("startActivityAndWait");
1243 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1244 userId, "startActivityAndWait");
1245 // TODO: Switch to user app stacks here.
1246 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1247 .setCaller(caller)
1248 .setCallingPackage(callingPackage)
1249 .setResolvedType(resolvedType)
1250 .setResultTo(resultTo)
1251 .setResultWho(resultWho)
1252 .setRequestCode(requestCode)
1253 .setStartFlags(startFlags)
1254 .setActivityOptions(bOptions)
1255 .setUserId(userId)
1256 .setProfilerInfo(profilerInfo)
1257 .setWaitResult(res)
1258 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001259 return res;
1260 }
1261
1262 @Override
1263 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1264 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1265 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001266 enforceNotIsolatedCaller("startActivityWithConfig");
1267 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1268 "startActivityWithConfig");
1269 // TODO: Switch to user app stacks here.
1270 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1271 .setCaller(caller)
1272 .setCallingPackage(callingPackage)
1273 .setResolvedType(resolvedType)
1274 .setResultTo(resultTo)
1275 .setResultWho(resultWho)
1276 .setRequestCode(requestCode)
1277 .setStartFlags(startFlags)
1278 .setGlobalConfiguration(config)
1279 .setActivityOptions(bOptions)
1280 .setUserId(userId)
1281 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 }
1283
Robert Carr8a2f9132019-11-11 15:03:15 -08001284 @Override
1285 public final void registerTaskOrganizer(ITaskOrganizer organizer, int windowingMode) {
1286 enforceCallerIsRecentsOrHasPermission(
1287 MANAGE_ACTIVITY_STACKS, "registerTaskOrganizer()");
1288 synchronized (mGlobalLock) {
1289 mTaskOrganizerController.registerTaskOrganizer(organizer, windowingMode);
1290 }
1291 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001292
1293 @Override
1294 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1295 int callingUid = Binder.getCallingUid();
1296 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1297 throw new SecurityException("Only the system process can request a permission token, "
1298 + "received request from uid: " + callingUid);
1299 }
1300 IBinder permissionToken = new Binder();
1301 synchronized (mGlobalLock) {
1302 mStartActivitySources.put(permissionToken, delegatorToken);
1303 }
1304
1305 Message expireMsg = PooledLambda.obtainMessage(
1306 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1307 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1308
1309 Message forgetMsg = PooledLambda.obtainMessage(
1310 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1311 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1312
1313 return permissionToken;
1314 }
1315
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001316 @Override
1317 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1318 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001319 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1320 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001321 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 // permission grants) as any app that may launch one of your own activities. So we only
1323 // allow this in two cases:
1324 // 1) The caller is an activity that is part of the core framework, and then only when it
1325 // is running as the system.
1326 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1327 // can only be requested by a system activity, which may then delegate this call to
1328 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 final ActivityRecord sourceRecord;
1330 final int targetUid;
1331 final String targetPackage;
1332 final boolean isResolver;
1333 synchronized (mGlobalLock) {
1334 if (resultTo == null) {
1335 throw new SecurityException("Must be called from an activity");
1336 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001337 final IBinder sourceToken;
1338 if (permissionToken != null) {
1339 // To even attempt to use a permissionToken, an app must also have this signature
1340 // permission.
1341 mAmInternal.enforceCallingPermission(
1342 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1343 "startActivityAsCaller");
1344 // If called with a permissionToken, we want the sourceRecord from the delegator
1345 // activity that requested this token.
1346 sourceToken = mStartActivitySources.remove(permissionToken);
1347 if (sourceToken == null) {
1348 // Invalid permissionToken, check if it recently expired.
1349 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1350 throw new SecurityException("Called with expired permission token: "
1351 + permissionToken);
1352 } else {
1353 throw new SecurityException("Called with invalid permission token: "
1354 + permissionToken);
1355 }
1356 }
1357 } else {
1358 // This method was called directly by the source.
1359 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001361
Louis Chang149d5c82019-12-30 09:47:39 +08001362 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001363 if (sourceRecord == null) {
1364 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 }
1366 if (sourceRecord.app == null) {
1367 throw new SecurityException("Called without a process attached to activity");
1368 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001369
1370 // Whether called directly or from a delegate, the source activity must be from the
1371 // android package.
1372 if (!sourceRecord.info.packageName.equals("android")) {
1373 throw new SecurityException("Must be called from an activity that is "
1374 + "declared in the android package");
1375 }
1376
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001377 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 // This is still okay, as long as this activity is running under the
1379 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001380 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001382 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001383 + " must be system uid or original calling uid "
1384 + sourceRecord.launchedFromUid);
1385 }
1386 }
1387 if (ignoreTargetSecurity) {
1388 if (intent.getComponent() == null) {
1389 throw new SecurityException(
1390 "Component must be specified with ignoreTargetSecurity");
1391 }
1392 if (intent.getSelector() != null) {
1393 throw new SecurityException(
1394 "Selector not allowed with ignoreTargetSecurity");
1395 }
1396 }
1397 targetUid = sourceRecord.launchedFromUid;
1398 targetPackage = sourceRecord.launchedFromPackage;
1399 isResolver = sourceRecord.isResolverOrChildActivity();
1400 }
1401
1402 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001403 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 }
1405
1406 // TODO: Switch to user app stacks here.
1407 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001408 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 .setCallingUid(targetUid)
1410 .setCallingPackage(targetPackage)
1411 .setResolvedType(resolvedType)
1412 .setResultTo(resultTo)
1413 .setResultWho(resultWho)
1414 .setRequestCode(requestCode)
1415 .setStartFlags(startFlags)
1416 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001417 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1419 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001420 // The target may well be in the background, which would normally prevent it
1421 // from starting an activity. Here we definitely want the start to succeed.
1422 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001423 .execute();
1424 } catch (SecurityException e) {
1425 // XXX need to figure out how to propagate to original app.
1426 // A SecurityException here is generally actually a fault of the original
1427 // calling activity (such as a fairly granting permissions), so propagate it
1428 // back to them.
1429 /*
1430 StringBuilder msg = new StringBuilder();
1431 msg.append("While launching");
1432 msg.append(intent.toString());
1433 msg.append(": ");
1434 msg.append(e.getMessage());
1435 */
1436 throw e;
1437 }
1438 }
1439
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001440 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1441 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001442 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 }
1444
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 @Override
1446 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1447 Intent intent, String resolvedType, IVoiceInteractionSession session,
1448 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1449 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001450 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001451 if (session == null || interactor == null) {
1452 throw new NullPointerException("null session or interactor");
1453 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001454 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001456 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 .setCallingUid(callingUid)
1458 .setCallingPackage(callingPackage)
1459 .setResolvedType(resolvedType)
1460 .setVoiceSession(session)
1461 .setVoiceInteractor(interactor)
1462 .setStartFlags(startFlags)
1463 .setProfilerInfo(profilerInfo)
1464 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001465 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001466 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 .execute();
1468 }
1469
1470 @Override
1471 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1472 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001473 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1474 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001476 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 .setCallingUid(callingUid)
1478 .setCallingPackage(callingPackage)
1479 .setResolvedType(resolvedType)
1480 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001481 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001482 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 .execute();
1484 }
1485
Riddle Hsu609a8e22019-06-27 16:46:29 -06001486 /**
1487 * Start the recents activity to perform the recents animation.
1488 *
1489 * @param intent The intent to start the recents activity.
1490 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1491 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001493 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1494 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001495 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001497 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001498 final long origId = Binder.clearCallingIdentity();
1499 try {
1500 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001501 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1502 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001503 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504
1505 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001506 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001507 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001508 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001509 if (recentsAnimationRunner == null) {
1510 anim.preloadRecentsActivity();
1511 } else {
1512 anim.startRecentsActivity(recentsAnimationRunner);
1513 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001514 }
1515 } finally {
1516 Binder.restoreCallingIdentity(origId);
1517 }
1518 }
1519
1520 @Override
1521 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001522 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 "startActivityFromRecents()");
1524
1525 final int callingPid = Binder.getCallingPid();
1526 final int callingUid = Binder.getCallingUid();
1527 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1528 final long origId = Binder.clearCallingIdentity();
1529 try {
1530 synchronized (mGlobalLock) {
1531 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1532 safeOptions);
1533 }
1534 } finally {
1535 Binder.restoreCallingIdentity(origId);
1536 }
1537 }
1538
1539 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001540 * Public API to check if the client is allowed to start an activity on specified display.
1541 *
1542 * If the target display is private or virtual, some restrictions will apply.
1543 *
1544 * @param displayId Target display id.
1545 * @param intent Intent used to launch the activity.
1546 * @param resolvedType The MIME type of the intent.
1547 * @param userId The id of the user for whom the call is made.
1548 * @return {@code true} if a call to start an activity on the target display should succeed and
1549 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1550 */
1551 @Override
1552 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1553 String resolvedType, int userId) {
1554 final int callingUid = Binder.getCallingUid();
1555 final int callingPid = Binder.getCallingPid();
1556 final long origId = Binder.clearCallingIdentity();
1557
1558 try {
1559 // Collect information about the target of the Intent.
1560 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1561 0 /* startFlags */, null /* profilerInfo */, userId,
1562 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1563 UserHandle.USER_NULL));
1564 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1565
1566 synchronized (mGlobalLock) {
1567 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1568 aInfo);
1569 }
1570 } finally {
1571 Binder.restoreCallingIdentity(origId);
1572 }
1573 }
1574
1575 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 * This is the internal entry point for handling Activity.finish().
1577 *
1578 * @param token The Binder token referencing the Activity we want to finish.
1579 * @param resultCode Result code, if any, from this Activity.
1580 * @param resultData Result data (Intent), if any, from this Activity.
1581 * @param finishTask Whether to finish the task associated with this Activity.
1582 *
1583 * @return Returns true if the activity successfully finished, or false if it is still running.
1584 */
1585 @Override
1586 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1587 int finishTask) {
1588 // Refuse possible leaked file descriptors
1589 if (resultData != null && resultData.hasFileDescriptors()) {
1590 throw new IllegalArgumentException("File descriptors passed in Intent");
1591 }
1592
1593 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001594 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 if (r == null) {
1596 return true;
1597 }
1598 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001599 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001600 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001601 if (rootR == null) {
1602 Slog.w(TAG, "Finishing task with all activities already finished");
1603 }
1604 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1605 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001606 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001607 return false;
1608 }
1609
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001610 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1611 // We should consolidate.
1612 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001614 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001615 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001616 if (next != null) {
1617 // ask watcher if this is allowed
1618 boolean resumeOK = true;
1619 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001620 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001622 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001623 Watchdog.getInstance().setActivityController(null);
1624 }
1625
1626 if (!resumeOK) {
1627 Slog.i(TAG, "Not finishing activity because controller resumed");
1628 return false;
1629 }
1630 }
1631 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001632
1633 // note down that the process has finished an activity and is in background activity
1634 // starts grace period
1635 if (r.app != null) {
1636 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1637 }
1638
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001639 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001640 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 try {
1642 boolean res;
1643 final boolean finishWithRootActivity =
1644 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1645 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1646 || (finishWithRootActivity && r == rootR)) {
1647 // If requested, remove the task that is associated to this activity only if it
1648 // was the root activity in the task. The result code and data is ignored
1649 // because we don't support returning them across task boundaries. Also, to
1650 // keep backwards compatibility we remove the task from recents when finishing
1651 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001652 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001654 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001655 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001656 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001658 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001659 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 if (!res) {
1661 Slog.i(TAG, "Failed to finish by app-request");
1662 }
1663 }
1664 return res;
1665 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001666 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 Binder.restoreCallingIdentity(origId);
1668 }
1669 }
1670 }
1671
1672 @Override
1673 public boolean finishActivityAffinity(IBinder token) {
1674 synchronized (mGlobalLock) {
1675 final long origId = Binder.clearCallingIdentity();
1676 try {
1677 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1678 if (r == null) {
1679 return false;
1680 }
1681
1682 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1683 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001684 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 return false;
1686 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001687
1688 final PooledFunction p = PooledLambda.obtainFunction(
1689 ActivityRecord::finishIfSameAffinity, r,
1690 PooledLambda.__(ActivityRecord.class));
1691 r.getTask().forAllActivities(
1692 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1693 p.recycle();
1694
Andrii Kuliande93eff2019-07-12 12:21:27 -07001695 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001696 } finally {
1697 Binder.restoreCallingIdentity(origId);
1698 }
1699 }
1700 }
1701
1702 @Override
1703 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1704 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001705 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001706 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001707 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001708 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1709 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001710 return;
1711 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001712 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1713 false /* processPausingActivities */, config);
1714 if (stopProfiling && r.hasProcess()) {
1715 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001716 }
1717 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001718 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001719 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001720 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 }
1723
1724 @Override
1725 public final void activityResumed(IBinder token) {
1726 final long origId = Binder.clearCallingIdentity();
1727 synchronized (mGlobalLock) {
1728 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 }
1730 Binder.restoreCallingIdentity(origId);
1731 }
1732
1733 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001734 public final void activityTopResumedStateLost() {
1735 final long origId = Binder.clearCallingIdentity();
1736 synchronized (mGlobalLock) {
1737 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1738 }
1739 Binder.restoreCallingIdentity(origId);
1740 }
1741
1742 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001743 public final void activityPaused(IBinder token) {
1744 final long origId = Binder.clearCallingIdentity();
1745 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001746 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001747 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1748 if (r != null) {
1749 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001750 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001751 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 }
1753 Binder.restoreCallingIdentity(origId);
1754 }
1755
1756 @Override
1757 public final void activityStopped(IBinder token, Bundle icicle,
1758 PersistableBundle persistentState, CharSequence description) {
1759 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1760
1761 // Refuse possible leaked file descriptors
1762 if (icicle != null && icicle.hasFileDescriptors()) {
1763 throw new IllegalArgumentException("File descriptors passed in Bundle");
1764 }
1765
1766 final long origId = Binder.clearCallingIdentity();
1767
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001768 String restartingName = null;
1769 int restartingUid = 0;
1770 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001772 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001773 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001774 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001775 if (r.attachedToProcess()
1776 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1777 // The activity was requested to restart from
1778 // {@link #restartActivityProcessIfVisible}.
1779 restartingName = r.app.mName;
1780 restartingUid = r.app.mUid;
1781 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001782 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001783 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001784 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001785 }
1786
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001787 if (restartingName != null) {
1788 // In order to let the foreground activity can be restarted with its saved state from
1789 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1790 // until the activity reports stopped with the state. And the activity record will be
1791 // kept because the record state is restarting, then the activity will be restarted
1792 // immediately if it is still the top one.
1793 mStackSupervisor.removeRestartTimeouts(r);
1794 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1795 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001796 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001797
1798 Binder.restoreCallingIdentity(origId);
1799 }
1800
1801 @Override
1802 public final void activityDestroyed(IBinder token) {
1803 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1804 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001805 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001806 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001807 try {
1808 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1809 if (activity != null) {
1810 activity.destroyed("activityDestroyed");
1811 }
1812 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001813 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001814 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001815 }
1816 }
1817 }
1818
1819 @Override
1820 public final void activityRelaunched(IBinder token) {
1821 final long origId = Binder.clearCallingIdentity();
1822 synchronized (mGlobalLock) {
1823 mStackSupervisor.activityRelaunchedLocked(token);
1824 }
1825 Binder.restoreCallingIdentity(origId);
1826 }
1827
1828 public final void activitySlept(IBinder token) {
1829 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1830
1831 final long origId = Binder.clearCallingIdentity();
1832
1833 synchronized (mGlobalLock) {
1834 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1835 if (r != null) {
1836 mStackSupervisor.activitySleptLocked(r);
1837 }
1838 }
1839
1840 Binder.restoreCallingIdentity(origId);
1841 }
1842
1843 @Override
1844 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1845 synchronized (mGlobalLock) {
1846 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1847 if (r == null) {
1848 return;
1849 }
1850 final long origId = Binder.clearCallingIdentity();
1851 try {
1852 r.setRequestedOrientation(requestedOrientation);
1853 } finally {
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856 }
1857 }
1858
1859 @Override
1860 public int getRequestedOrientation(IBinder token) {
1861 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001862 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1863 return (r != null)
1864 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 }
1866 }
1867
1868 @Override
1869 public void setImmersive(IBinder token, boolean immersive) {
1870 synchronized (mGlobalLock) {
1871 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1872 if (r == null) {
1873 throw new IllegalArgumentException();
1874 }
1875 r.immersive = immersive;
1876
1877 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001878 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001880 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 }
1882 }
1883 }
1884
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 void applyUpdateLockStateLocked(ActivityRecord r) {
1886 // Modifications to the UpdateLock state are done on our handler, outside
1887 // the activity manager's locks. The new state is determined based on the
1888 // state *now* of the relevant activity record. The object is passed to
1889 // the handler solely for logging detail, not to be consulted/modified.
1890 final boolean nextState = r != null && r.immersive;
1891 mH.post(() -> {
1892 if (mUpdateLock.isHeld() != nextState) {
1893 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1894 "Applying new update lock state '" + nextState + "' for " + r);
1895 if (nextState) {
1896 mUpdateLock.acquire();
1897 } else {
1898 mUpdateLock.release();
1899 }
1900 }
1901 });
1902 }
1903
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 @Override
1905 public boolean isImmersive(IBinder token) {
1906 synchronized (mGlobalLock) {
1907 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1908 if (r == null) {
1909 throw new IllegalArgumentException();
1910 }
1911 return r.immersive;
1912 }
1913 }
1914
1915 @Override
1916 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001917 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001919 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 return (r != null) ? r.immersive : false;
1921 }
1922 }
1923
1924 @Override
1925 public void overridePendingTransition(IBinder token, String packageName,
1926 int enterAnim, int exitAnim) {
1927 synchronized (mGlobalLock) {
1928 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1929 if (self == null) {
1930 return;
1931 }
1932
1933 final long origId = Binder.clearCallingIdentity();
1934
1935 if (self.isState(
1936 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001937 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001938 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 }
1940
1941 Binder.restoreCallingIdentity(origId);
1942 }
1943 }
1944
1945 @Override
1946 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001947 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
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 return ActivityManager.COMPAT_MODE_UNKNOWN;
1952 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001953 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 }
1955 }
1956
1957 @Override
1958 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001959 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001963 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001964 if (r == null) {
1965 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1966 return;
1967 }
1968 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001969 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 }
1971 }
1972
1973 @Override
1974 public int getLaunchedFromUid(IBinder activityToken) {
1975 ActivityRecord srec;
1976 synchronized (mGlobalLock) {
1977 srec = ActivityRecord.forTokenLocked(activityToken);
1978 }
1979 if (srec == null) {
1980 return -1;
1981 }
1982 return srec.launchedFromUid;
1983 }
1984
1985 @Override
1986 public String getLaunchedFromPackage(IBinder activityToken) {
1987 ActivityRecord srec;
1988 synchronized (mGlobalLock) {
1989 srec = ActivityRecord.forTokenLocked(activityToken);
1990 }
1991 if (srec == null) {
1992 return null;
1993 }
1994 return srec.launchedFromPackage;
1995 }
1996
1997 @Override
1998 public boolean convertFromTranslucent(IBinder token) {
1999 final long origId = Binder.clearCallingIdentity();
2000 try {
2001 synchronized (mGlobalLock) {
2002 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2003 if (r == null) {
2004 return false;
2005 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002006 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 }
2008 } finally {
2009 Binder.restoreCallingIdentity(origId);
2010 }
2011 }
2012
2013 @Override
2014 public boolean convertToTranslucent(IBinder token, Bundle options) {
2015 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2016 final long origId = Binder.clearCallingIdentity();
2017 try {
2018 synchronized (mGlobalLock) {
2019 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2020 if (r == null) {
2021 return false;
2022 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002023 final ActivityRecord under = r.getTask().getActivityBelow(r);
2024 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2026 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002027 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 } finally {
2030 Binder.restoreCallingIdentity(origId);
2031 }
2032 }
2033
2034 @Override
2035 public void notifyActivityDrawn(IBinder token) {
2036 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2037 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002038 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002039 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002040 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002041 }
2042 }
2043 }
2044
2045 @Override
2046 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2047 synchronized (mGlobalLock) {
2048 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2049 if (r == null) {
2050 return;
2051 }
2052 r.reportFullyDrawnLocked(restoredFromBundle);
2053 }
2054 }
2055
2056 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002057 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 synchronized (mGlobalLock) {
2059 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002060 if (stack != null) {
2061 final int displayId = stack.getDisplayId();
2062 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 return DEFAULT_DISPLAY;
2065 }
2066 }
2067
2068 @Override
2069 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002070 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 long ident = Binder.clearCallingIdentity();
2072 try {
2073 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002074 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002076 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 }
2078 return null;
2079 }
2080 } finally {
2081 Binder.restoreCallingIdentity(ident);
2082 }
2083 }
2084
2085 @Override
2086 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002087 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002088 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2089 final long callingId = Binder.clearCallingIdentity();
2090 try {
2091 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002092 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002093 if (stack == null) {
2094 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2095 return;
2096 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002097 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002098 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002099 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002100 }
2101 }
2102 } finally {
2103 Binder.restoreCallingIdentity(callingId);
2104 }
2105 }
2106
2107 @Override
2108 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002109 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2111 final long callingId = Binder.clearCallingIdentity();
2112 try {
2113 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002114 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002115 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002116 if (task == null) {
2117 return;
2118 }
2119 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002120 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002121 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 }
2123 }
2124 } finally {
2125 Binder.restoreCallingIdentity(callingId);
2126 }
2127 }
2128
2129 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002130 public void restartActivityProcessIfVisible(IBinder activityToken) {
2131 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2132 final long callingId = Binder.clearCallingIdentity();
2133 try {
2134 synchronized (mGlobalLock) {
2135 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2136 if (r == null) {
2137 return;
2138 }
2139 r.restartProcessIfVisible();
2140 }
2141 } finally {
2142 Binder.restoreCallingIdentity(callingId);
2143 }
2144 }
2145
2146 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002148 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 synchronized (mGlobalLock) {
2150 final long ident = Binder.clearCallingIdentity();
2151 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002152 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 "remove-task");
2154 } finally {
2155 Binder.restoreCallingIdentity(ident);
2156 }
2157 }
2158 }
2159
2160 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002161 public void removeAllVisibleRecentTasks() {
2162 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2163 synchronized (mGlobalLock) {
2164 final long ident = Binder.clearCallingIdentity();
2165 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002166 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002167 } finally {
2168 Binder.restoreCallingIdentity(ident);
2169 }
2170 }
2171 }
2172
2173 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2175 synchronized (mGlobalLock) {
2176 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2177 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002178 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 }
2180 }
2181 return false;
2182 }
2183
2184 @Override
2185 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2186 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002187
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002188 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002189 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2190 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002191 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002192 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002193 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002194 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 }
2196 }
2197
2198 /**
2199 * Attempts to move a task backwards in z-order (the order of activities within the task is
2200 * unchanged).
2201 *
2202 * There are several possible results of this call:
2203 * - if the task is locked, then we will show the lock toast
2204 * - if there is a task behind the provided task, then that task is made visible and resumed as
2205 * this task is moved to the back
2206 * - otherwise, if there are no other tasks in the stack:
2207 * - if this task is in the pinned stack, then we remove the stack completely, which will
2208 * have the effect of moving the task to the top or bottom of the fullscreen stack
2209 * (depending on whether it is visible)
2210 * - otherwise, we simply return home and hide this task
2211 *
2212 * @param token A reference to the activity we wish to move
2213 * @param nonRoot If false then this only works if the activity is the root
2214 * of a task; if true it will work for any activity in a task.
2215 * @return Returns true if the move completed, false if not.
2216 */
2217 @Override
2218 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002219 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220 synchronized (mGlobalLock) {
2221 final long origId = Binder.clearCallingIdentity();
2222 try {
2223 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002224 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002226 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002227 }
2228 } finally {
2229 Binder.restoreCallingIdentity(origId);
2230 }
2231 }
2232 return false;
2233 }
2234
2235 @Override
2236 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002237 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 long ident = Binder.clearCallingIdentity();
2239 Rect rect = new Rect();
2240 try {
2241 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002242 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002243 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2244 if (task == null) {
2245 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2246 return rect;
2247 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002248 if (task.getParent() != null) {
2249 rect.set(task.getBounds());
2250 } else if (task.mLastNonFullscreenBounds != null) {
2251 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002252 }
2253 }
2254 } finally {
2255 Binder.restoreCallingIdentity(ident);
2256 }
2257 return rect;
2258 }
2259
2260 @Override
2261 public ActivityManager.TaskDescription getTaskDescription(int id) {
2262 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002263 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002264 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002265 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002266 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2267 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002268 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 }
2270 }
2271 return null;
2272 }
2273
2274 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002275 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2276 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2277 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2278 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2279 return;
2280 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002281 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002282 synchronized (mGlobalLock) {
2283 final long ident = Binder.clearCallingIdentity();
2284 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002285 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002286 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002287 if (task == null) {
2288 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2289 return;
2290 }
2291
2292 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2293 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2294
2295 if (!task.isActivityTypeStandardOrUndefined()) {
2296 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2297 + " non-standard task " + taskId + " to windowing mode="
2298 + windowingMode);
2299 }
2300
2301 final ActivityStack stack = task.getStack();
2302 if (toTop) {
2303 stack.moveToFront("setTaskWindowingMode", task);
2304 }
2305 stack.setWindowingMode(windowingMode);
2306 } finally {
2307 Binder.restoreCallingIdentity(ident);
2308 }
2309 }
2310 }
2311
2312 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002313 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002314 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315 ActivityRecord r = getCallingRecordLocked(token);
2316 return r != null ? r.info.packageName : null;
2317 }
2318 }
2319
2320 @Override
2321 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002322 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002323 ActivityRecord r = getCallingRecordLocked(token);
2324 return r != null ? r.intent.getComponent() : null;
2325 }
2326 }
2327
2328 private ActivityRecord getCallingRecordLocked(IBinder token) {
2329 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2330 if (r == null) {
2331 return null;
2332 }
2333 return r.resultTo;
2334 }
2335
2336 @Override
2337 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002338 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339
2340 synchronized (mGlobalLock) {
2341 final long origId = Binder.clearCallingIdentity();
2342 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002343 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002344 } finally {
2345 Binder.restoreCallingIdentity(origId);
2346 }
2347 }
2348 }
2349
Mark Renouf446251d2019-04-26 10:22:41 -04002350 @Override
2351 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2352 synchronized (mGlobalLock) {
2353 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2354 if (r == null) {
2355 return;
2356 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002357 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002358 if (stack != null && stack.isSingleTaskInstance()) {
2359 // Single-task stacks are used for activities which are presented in floating
2360 // windows above full screen activities. Instead of directly finishing the
2361 // task, a task change listener is used to notify SystemUI so the action can be
2362 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002363 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002364 mTaskChangeNotificationController
2365 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2366 } else {
2367 try {
2368 callback.requestFinish();
2369 } catch (RemoteException e) {
2370 Slog.e(TAG, "Failed to invoke request finish callback", e);
2371 }
2372 }
2373 }
2374 }
2375
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 /**
2377 * TODO: Add mController hook
2378 */
2379 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002380 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2381 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002382 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383
2384 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2385 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002386 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2387 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 }
2389 }
2390
Ricky Waiaca8a772019-04-04 16:01:06 +01002391 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2392 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002394
Ricky Waiaca8a772019-04-04 16:01:06 +01002395 final int callingPid = Binder.getCallingPid();
2396 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002397 if (!isSameApp(callingUid, callingPackage)) {
2398 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2399 + Binder.getCallingPid() + " as package " + callingPackage;
2400 Slog.w(TAG, msg);
2401 throw new SecurityException(msg);
2402 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002403 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 SafeActivityOptions.abort(options);
2405 return;
2406 }
2407 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002408 WindowProcessController callerApp = null;
2409 if (appThread != null) {
2410 callerApp = getProcessController(appThread);
2411 }
2412 final ActivityStarter starter = getActivityStartController().obtainStarter(
2413 null /* intent */, "moveTaskToFront");
2414 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2415 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002416 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002417 return;
2418 }
2419 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002421 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002422 if (task == null) {
2423 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002424 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002425 return;
2426 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002427 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002428 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002429 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 return;
2431 }
2432 ActivityOptions realOptions = options != null
2433 ? options.getOptions(mStackSupervisor)
2434 : null;
2435 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2436 false /* forceNonResizable */);
2437
Wale Ogunwale21e06482019-11-18 05:14:15 -08002438 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002439 if (topActivity != null) {
2440
2441 // We are reshowing a task, use a starting window to hide the initial draw delay
2442 // so the transition can start earlier.
2443 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2444 true /* taskSwitch */, fromRecents);
2445 }
2446 } finally {
2447 Binder.restoreCallingIdentity(origId);
2448 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449 }
2450
Ricky Waiaca8a772019-04-04 16:01:06 +01002451 /**
2452 * Return true if callingUid is system, or packageName belongs to that callingUid.
2453 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002454 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002455 try {
2456 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2457 if (packageName == null) {
2458 return false;
2459 }
2460 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2461 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2462 UserHandle.getUserId(callingUid));
2463 return UserHandle.isSameApp(callingUid, uid);
2464 }
2465 } catch (RemoteException e) {
2466 // Should not happen
2467 }
2468 return true;
2469 }
2470
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002471 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2472 int callingPid, int callingUid, String name) {
2473 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2474 return true;
2475 }
2476
2477 if (getRecentTasks().isCallerRecents(sourceUid)) {
2478 return true;
2479 }
2480
2481 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2482 if (perm == PackageManager.PERMISSION_GRANTED) {
2483 return true;
2484 }
2485 if (checkAllowAppSwitchUid(sourceUid)) {
2486 return true;
2487 }
2488
2489 // If the actual IPC caller is different from the logical source, then
2490 // also see if they are allowed to control app switches.
2491 if (callingUid != -1 && callingUid != sourceUid) {
2492 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2493 if (perm == PackageManager.PERMISSION_GRANTED) {
2494 return true;
2495 }
2496 if (checkAllowAppSwitchUid(callingUid)) {
2497 return true;
2498 }
2499 }
2500
2501 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2502 return false;
2503 }
2504
2505 private boolean checkAllowAppSwitchUid(int uid) {
2506 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2507 if (types != null) {
2508 for (int i = types.size() - 1; i >= 0; i--) {
2509 if (types.valueAt(i).intValue() == uid) {
2510 return true;
2511 }
2512 }
2513 }
2514 return false;
2515 }
2516
2517 @Override
2518 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2519 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2520 "setActivityController()");
2521 synchronized (mGlobalLock) {
2522 mController = controller;
2523 mControllerIsAMonkey = imAMonkey;
2524 Watchdog.getInstance().setActivityController(controller);
2525 }
2526 }
2527
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002528 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 synchronized (mGlobalLock) {
2530 return mController != null && mControllerIsAMonkey;
2531 }
2532 }
2533
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 @Override
2535 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2536 synchronized (mGlobalLock) {
2537 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2538 }
2539 }
2540
2541 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002542 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2543 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2544 }
2545
2546 @Override
2547 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2548 @WindowConfiguration.ActivityType int ignoreActivityType,
2549 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2550 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002551 final int callingPid = Binder.getCallingPid();
2552 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002553 final int[] profileIds = getUserManager().getProfileIds(
2554 UserHandle.getUserId(callingUid), true);
2555 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2556 for (int i = 0; i < profileIds.length; i++) {
2557 callingProfileIds.add(profileIds[i]);
2558 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002559 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2560
2561 synchronized (mGlobalLock) {
2562 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2563
Nicholas Sauer0259e532019-08-30 08:24:55 -07002564 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002565 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002566 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 }
2568
2569 return list;
2570 }
2571
2572 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002573 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2574 synchronized (mGlobalLock) {
2575 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002576 try {
2577 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2578 if (r == null) return;
2579
2580 final PooledConsumer c = PooledLambda.obtainConsumer(
2581 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2582 r, resultWho, requestCode);
2583 // TODO: This should probably only loop over the task since you need to be in the
2584 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002585 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002586 c.recycle();
2587
2588 updateOomAdj();
2589 } finally {
2590 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002592 }
2593 }
2594
2595 @Override
2596 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 ActivityStack stack = ActivityRecord.getStackLocked(token);
2599 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002600 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002601 }
2602 return false;
2603 }
2604 }
2605
2606 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002607 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002608 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609 synchronized (mGlobalLock) {
2610 final long ident = Binder.clearCallingIdentity();
2611 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002612 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 if (task == null) {
2614 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2615 return;
2616 }
2617
2618 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2619 + " to stackId=" + stackId + " toTop=" + toTop);
2620
Louis Chang149d5c82019-12-30 09:47:39 +08002621 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002622 if (stack == null) {
2623 throw new IllegalStateException(
2624 "moveTaskToStack: No stack for stackId=" + stackId);
2625 }
2626 if (!stack.isActivityTypeStandardOrUndefined()) {
2627 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2628 + taskId + " to stack " + stackId);
2629 }
2630 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002631 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002632 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2633 }
2634 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2635 "moveTaskToStack");
2636 } finally {
2637 Binder.restoreCallingIdentity(ident);
2638 }
2639 }
2640 }
2641
2642 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002643 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2644 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645
2646 final long ident = Binder.clearCallingIdentity();
2647 try {
2648 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002649 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002650 if (stack == null) {
2651 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2652 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002653 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002654 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2655 throw new IllegalArgumentException("Stack: " + stackId
2656 + " doesn't support animated resize.");
2657 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002658 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002659 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002660 }
2661 } finally {
2662 Binder.restoreCallingIdentity(ident);
2663 }
2664 }
2665
wilsonshih5c4cf522019-01-25 09:03:47 +08002666 @Override
2667 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2668 int animationDuration) {
2669 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2670
2671 final long ident = Binder.clearCallingIdentity();
2672 try {
2673 synchronized (mGlobalLock) {
2674 if (xOffset == 0 && yOffset == 0) {
2675 return;
2676 }
Louis Chang149d5c82019-12-30 09:47:39 +08002677 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002678 if (stack == null) {
2679 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2680 return;
2681 }
2682 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2683 throw new IllegalArgumentException("Stack: " + stackId
2684 + " doesn't support animated resize.");
2685 }
2686 final Rect destBounds = new Rect();
2687 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002688 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002689 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2690 return;
2691 }
2692 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002693 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002694 animationDuration, false /* fromFullscreen */);
2695 }
2696 } finally {
2697 Binder.restoreCallingIdentity(ident);
2698 }
2699 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 /**
2701 * Moves the specified task to the primary-split-screen stack.
2702 *
2703 * @param taskId Id of task to move.
2704 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2705 * exist already. See
2706 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2707 * and
2708 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2709 * @param toTop If the task and stack should be moved to the top.
2710 * @param animate Whether we should play an animation for the moving the task.
2711 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2712 * stack. Pass {@code null} to use default bounds.
2713 * @param showRecents If the recents activity should be shown on the other side of the task
2714 * going into split-screen mode.
2715 */
2716 @Override
2717 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2718 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002719 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002720 "setTaskWindowingModeSplitScreenPrimary()");
2721 synchronized (mGlobalLock) {
2722 final long ident = Binder.clearCallingIdentity();
2723 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002724 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002725 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002726 if (task == null) {
2727 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2728 return false;
2729 }
2730 if (DEBUG_STACK) Slog.d(TAG_STACK,
2731 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2732 + " to createMode=" + createMode + " toTop=" + toTop);
2733 if (!task.isActivityTypeStandardOrUndefined()) {
2734 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2735 + " non-standard task " + taskId + " to split-screen windowing mode");
2736 }
2737
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002738 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002739 final int windowingMode = task.getWindowingMode();
2740 final ActivityStack stack = task.getStack();
2741 if (toTop) {
2742 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2743 }
2744 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002745 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2746 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002747 return windowingMode != task.getWindowingMode();
2748 } finally {
2749 Binder.restoreCallingIdentity(ident);
2750 }
2751 }
2752 }
2753
2754 /**
2755 * Removes stacks in the input windowing modes from the system if they are of activity type
2756 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2757 */
2758 @Override
2759 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002761 "removeStacksInWindowingModes()");
2762
2763 synchronized (mGlobalLock) {
2764 final long ident = Binder.clearCallingIdentity();
2765 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002766 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002767 } finally {
2768 Binder.restoreCallingIdentity(ident);
2769 }
2770 }
2771 }
2772
2773 @Override
2774 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002776 "removeStacksWithActivityTypes()");
2777
2778 synchronized (mGlobalLock) {
2779 final long ident = Binder.clearCallingIdentity();
2780 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002781 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002782 } finally {
2783 Binder.restoreCallingIdentity(ident);
2784 }
2785 }
2786 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787
2788 @Override
2789 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2790 int userId) {
2791 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2793 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002794 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002795 final boolean detailed = checkGetTasksPermission(
2796 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2797 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 == PackageManager.PERMISSION_GRANTED;
2799
2800 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002801 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 callingUid);
2803 }
2804 }
2805
2806 @Override
2807 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002808 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 long ident = Binder.clearCallingIdentity();
2810 try {
2811 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002812 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 }
2814 } finally {
2815 Binder.restoreCallingIdentity(ident);
2816 }
2817 }
2818
2819 @Override
2820 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002821 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 long ident = Binder.clearCallingIdentity();
2823 try {
2824 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002825 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826 }
2827 } finally {
2828 Binder.restoreCallingIdentity(ident);
2829 }
2830 }
2831
2832 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002833 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2834 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2835 long ident = Binder.clearCallingIdentity();
2836 try {
2837 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002838 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002839 }
2840 } finally {
2841 Binder.restoreCallingIdentity(ident);
2842 }
2843 }
2844
2845 @Override
2846 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2847 int displayId) {
2848 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2849 long ident = Binder.clearCallingIdentity();
2850 try {
2851 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002852 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002853 }
2854 } finally {
2855 Binder.restoreCallingIdentity(ident);
2856 }
2857 }
2858
2859 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002860 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002861 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 final long callingUid = Binder.getCallingUid();
2863 final long origId = Binder.clearCallingIdentity();
2864 try {
2865 synchronized (mGlobalLock) {
2866 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002867 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2869 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2870 }
2871 } finally {
2872 Binder.restoreCallingIdentity(origId);
2873 }
2874 }
2875
2876 @Override
2877 public void startLockTaskModeByToken(IBinder token) {
2878 synchronized (mGlobalLock) {
2879 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2880 if (r == null) {
2881 return;
2882 }
Louis Changcdec0802019-11-11 11:45:07 +08002883 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 }
2885 }
2886
2887 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002888 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002889 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 // This makes inner call to look as if it was initiated by system.
2891 long ident = Binder.clearCallingIdentity();
2892 try {
2893 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002894 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002895 MATCH_TASK_IN_STACKS_ONLY);
2896 if (task == null) {
2897 return;
2898 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899
2900 // When starting lock task mode the stack must be in front and focused
2901 task.getStack().moveToFront("startSystemLockTaskMode");
2902 startLockTaskModeLocked(task, true /* isSystemCaller */);
2903 }
2904 } finally {
2905 Binder.restoreCallingIdentity(ident);
2906 }
2907 }
2908
2909 @Override
2910 public void stopLockTaskModeByToken(IBinder token) {
2911 synchronized (mGlobalLock) {
2912 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2913 if (r == null) {
2914 return;
2915 }
Louis Changcdec0802019-11-11 11:45:07 +08002916 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 }
2918 }
2919
2920 /**
2921 * This API should be called by SystemUI only when user perform certain action to dismiss
2922 * lock task mode. We should only dismiss pinned lock task mode in this case.
2923 */
2924 @Override
2925 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002926 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2928 }
2929
Louis Changcdec0802019-11-11 11:45:07 +08002930 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2932 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2933 return;
2934 }
2935
Louis Chang149d5c82019-12-30 09:47:39 +08002936 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002937 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 throw new IllegalArgumentException("Invalid task, not in foreground");
2939 }
2940
2941 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2942 // system or a specific app.
2943 // * System-initiated requests will only start the pinned mode (screen pinning)
2944 // * App-initiated requests
2945 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2946 // - will start the pinned mode, otherwise
2947 final int callingUid = Binder.getCallingUid();
2948 long ident = Binder.clearCallingIdentity();
2949 try {
2950 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002951 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002953 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 } finally {
2955 Binder.restoreCallingIdentity(ident);
2956 }
2957 }
2958
Louis Changcdec0802019-11-11 11:45:07 +08002959 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002960 final int callingUid = Binder.getCallingUid();
2961 long ident = Binder.clearCallingIdentity();
2962 try {
2963 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002964 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 }
2966 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2967 // task and jumping straight into a call in the case of emergency call back.
2968 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2969 if (tm != null) {
2970 tm.showInCallScreen(false);
2971 }
2972 } finally {
2973 Binder.restoreCallingIdentity(ident);
2974 }
2975 }
2976
2977 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002978 public void updateLockTaskPackages(int userId, String[] packages) {
2979 final int callingUid = Binder.getCallingUid();
2980 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2981 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2982 "updateLockTaskPackages()");
2983 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002984 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002985 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2986 + Arrays.toString(packages));
2987 getLockTaskController().updateLockTaskPackages(userId, packages);
2988 }
2989 }
2990
2991 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 public boolean isInLockTaskMode() {
2993 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2994 }
2995
2996 @Override
2997 public int getLockTaskModeState() {
2998 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002999 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003000 }
3001 }
3002
3003 @Override
3004 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3005 synchronized (mGlobalLock) {
3006 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3007 if (r != null) {
3008 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003009 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 }
3012 }
3013 }
3014
3015 @Override
3016 public Bundle getActivityOptions(IBinder token) {
3017 final long origId = Binder.clearCallingIdentity();
3018 try {
3019 synchronized (mGlobalLock) {
3020 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3021 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003022 final ActivityOptions activityOptions = r.takeOptionsLocked(
3023 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 return activityOptions == null ? null : activityOptions.toBundle();
3025 }
3026 return null;
3027 }
3028 } finally {
3029 Binder.restoreCallingIdentity(origId);
3030 }
3031 }
3032
3033 @Override
3034 public List<IBinder> getAppTasks(String callingPackage) {
3035 int callingUid = Binder.getCallingUid();
3036 long ident = Binder.clearCallingIdentity();
3037 try {
3038 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003039 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003040 }
3041 } finally {
3042 Binder.restoreCallingIdentity(ident);
3043 }
3044 }
3045
3046 @Override
3047 public void finishVoiceTask(IVoiceInteractionSession session) {
3048 synchronized (mGlobalLock) {
3049 final long origId = Binder.clearCallingIdentity();
3050 try {
3051 // TODO: VI Consider treating local voice interactions and voice tasks
3052 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003053 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 } finally {
3055 Binder.restoreCallingIdentity(origId);
3056 }
3057 }
3058
3059 }
3060
3061 @Override
3062 public boolean isTopOfTask(IBinder token) {
3063 synchronized (mGlobalLock) {
3064 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003065 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 }
3067 }
3068
3069 @Override
3070 public void notifyLaunchTaskBehindComplete(IBinder token) {
3071 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3072 }
3073
3074 @Override
3075 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003076 mH.post(() -> {
3077 synchronized (mGlobalLock) {
3078 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003079 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003080 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003081 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003082 } catch (RemoteException e) {
3083 }
3084 }
3085 }
3086
3087 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003088 }
3089
3090 /** Called from an app when assist data is ready. */
3091 @Override
3092 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3093 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003094 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 synchronized (pae) {
3096 pae.result = extras;
3097 pae.structure = structure;
3098 pae.content = content;
3099 if (referrer != null) {
3100 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3101 }
3102 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003103 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003104 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003105 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003106 structure.setHomeActivity(pae.isHome);
3107 }
3108 pae.haveResult = true;
3109 pae.notifyAll();
3110 if (pae.intent == null && pae.receiver == null) {
3111 // Caller is just waiting for the result.
3112 return;
3113 }
3114 }
3115 // We are now ready to launch the assist activity.
3116 IAssistDataReceiver sendReceiver = null;
3117 Bundle sendBundle = null;
3118 synchronized (mGlobalLock) {
3119 buildAssistBundleLocked(pae, extras);
3120 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003121 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 if (!exists) {
3123 // Timed out.
3124 return;
3125 }
3126
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003127 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003128 // Caller wants result sent back to them.
3129 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003130 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003131 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003132 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3133 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003134 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3135 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3136 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3137 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3138 }
3139 }
3140 if (sendReceiver != null) {
3141 try {
3142 sendReceiver.onHandleAssistData(sendBundle);
3143 } catch (RemoteException e) {
3144 }
3145 return;
3146 }
3147
3148 final long ident = Binder.clearCallingIdentity();
3149 try {
3150 if (TextUtils.equals(pae.intent.getAction(),
3151 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003152 // Start voice interaction through VoiceInteractionManagerService.
3153 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3154 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003155 } else {
3156 pae.intent.replaceExtras(pae.extras);
3157 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3158 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3159 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003160 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161
3162 try {
3163 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3164 } catch (ActivityNotFoundException e) {
3165 Slog.w(TAG, "No activity to handle assist action.", e);
3166 }
3167 }
3168 } finally {
3169 Binder.restoreCallingIdentity(ident);
3170 }
3171 }
3172
3173 @Override
3174 public int addAppTask(IBinder activityToken, Intent intent,
3175 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3176 final int callingUid = Binder.getCallingUid();
3177 final long callingIdent = Binder.clearCallingIdentity();
3178
3179 try {
3180 synchronized (mGlobalLock) {
3181 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3182 if (r == null) {
3183 throw new IllegalArgumentException("Activity does not exist; token="
3184 + activityToken);
3185 }
3186 ComponentName comp = intent.getComponent();
3187 if (comp == null) {
3188 throw new IllegalArgumentException("Intent " + intent
3189 + " must specify explicit component");
3190 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003191 if (thumbnail.getWidth() != mThumbnailWidth
3192 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 throw new IllegalArgumentException("Bad thumbnail size: got "
3194 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003195 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 if (intent.getSelector() != null) {
3198 intent.setSelector(null);
3199 }
3200 if (intent.getSourceBounds() != null) {
3201 intent.setSourceBounds(null);
3202 }
3203 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3204 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3205 // The caller has added this as an auto-remove task... that makes no
3206 // sense, so turn off auto-remove.
3207 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3208 }
3209 }
3210 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3211 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3212 if (ainfo.applicationInfo.uid != callingUid) {
3213 throw new SecurityException(
3214 "Can't add task for another application: target uid="
3215 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3216 }
3217
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003218 final ActivityStack stack = r.getRootTask();
Louis Changcdec0802019-11-11 11:45:07 +08003219 final Task task = stack.createTask(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08003220 mStackSupervisor.getNextTaskIdForUser(r.mUserId), ainfo, intent, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003221 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003223 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003224 return INVALID_TASK_ID;
3225 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003226 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227
3228 // TODO: Send the thumbnail to WM to store it.
3229
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003230 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003231 }
3232 } finally {
3233 Binder.restoreCallingIdentity(callingIdent);
3234 }
3235 }
3236
3237 @Override
3238 public Point getAppTaskThumbnailSize() {
3239 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003240 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 }
3242 }
3243
3244 @Override
3245 public void setTaskResizeable(int taskId, int resizeableMode) {
3246 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003247 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003248 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3249 if (task == null) {
3250 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3251 return;
3252 }
3253 task.setResizeMode(resizeableMode);
3254 }
3255 }
3256
3257 @Override
3258 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003259 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003260 long ident = Binder.clearCallingIdentity();
3261 try {
3262 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003263 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003264 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003265 if (task == null) {
3266 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3267 return;
3268 }
3269 // Place the task in the right stack if it isn't there already based on
3270 // the requested bounds.
3271 // The stack transition logic is:
3272 // - a null bounds on a freeform task moves that task to fullscreen
3273 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3274 // that task to freeform
3275 // - otherwise the task is not moved
3276 ActivityStack stack = task.getStack();
3277 if (!task.getWindowConfiguration().canResizeTask()) {
3278 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3279 }
3280 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3281 stack = stack.getDisplay().getOrCreateStack(
3282 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3283 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3284 stack = stack.getDisplay().getOrCreateStack(
3285 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3286 }
3287
3288 // Reparent the task to the right stack if necessary
3289 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3290 if (stack != task.getStack()) {
3291 // Defer resume until the task is resized below
3292 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3293 DEFER_RESUME, "resizeTask");
3294 preserveWindow = false;
3295 }
3296
3297 // After reparenting (which only resizes the task to the stack bounds), resize the
3298 // task to the actual bounds provided
3299 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3300 }
3301 } finally {
3302 Binder.restoreCallingIdentity(ident);
3303 }
3304 }
3305
Evan Roskya80f11c2020-01-23 19:17:10 -08003306 private int sanitizeAndApplyChange(WindowContainer container,
Evan Roskyddedfd42019-10-04 13:38:38 -07003307 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003308 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003309 throw new RuntimeException("Invalid token in task transaction");
3310 }
3311 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3312 // masks here.
3313 int configMask = change.getConfigSetMask();
3314 int windowMask = change.getWindowSetMask();
3315 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3316 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3317 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
Evan Rosky226de132020-01-03 18:00:29 -08003318 int effects = 0;
3319 if (configMask != 0) {
3320 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3321 c.setTo(change.getConfiguration(), configMask, windowMask);
3322 container.onRequestedOverrideConfigurationChanged(c);
3323 // TODO(b/145675353): remove the following once we could apply new bounds to the
3324 // pinned stack together with its children.
3325 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3326 effects |= TRANSACT_EFFECTS_CLIENT_CONFIG;
3327 }
3328 if ((change.getChangeMask() & WindowContainerTransaction.Change.CHANGE_FOCUSABLE) != 0) {
3329 if (container.setFocusable(change.getFocusable())) {
3330 effects |= TRANSACT_EFFECTS_LIFECYCLE;
3331 }
3332 }
3333 return effects;
Hongwei Wangebf18082019-09-26 14:25:11 -07003334 }
3335
3336 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3337 int windowMask, Configuration config) {
3338 if ((container instanceof ActivityStack)
3339 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3340 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3341 final ActivityStack stack = (ActivityStack) container;
3342 if (stack.inPinnedWindowingMode()) {
3343 stack.resize(config.windowConfiguration.getBounds(),
3344 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3345 PRESERVE_WINDOWS, true /* deferResume */);
3346 }
3347 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003348 }
3349
Evan Roskya80f11c2020-01-23 19:17:10 -08003350 private int applyWindowContainerChange(WindowContainer wc,
Robert Carr8a2f9132019-11-11 15:03:15 -08003351 WindowContainerTransaction.Change c) {
Evan Roskya80f11c2020-01-23 19:17:10 -08003352 int effects = sanitizeAndApplyChange(wc, c);
Robert Carr8a2f9132019-11-11 15:03:15 -08003353
3354 Rect enterPipBounds = c.getEnterPipBounds();
3355 if (enterPipBounds != null) {
Evan Roskya80f11c2020-01-23 19:17:10 -08003356 Task tr = (Task) wc;
Robert Carr8a2f9132019-11-11 15:03:15 -08003357 mStackSupervisor.updatePictureInPictureMode(tr,
3358 enterPipBounds, true);
3359 }
Evan Rosky226de132020-01-03 18:00:29 -08003360 return effects;
Robert Carr8a2f9132019-11-11 15:03:15 -08003361 }
3362
Evan Roskyddedfd42019-10-04 13:38:38 -07003363 @Override
3364 public void applyContainerTransaction(WindowContainerTransaction t) {
3365 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
Evan Rosky226de132020-01-03 18:00:29 -08003366 if (t == null) {
3367 return;
3368 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003369 long ident = Binder.clearCallingIdentity();
3370 try {
Evan Roskyddedfd42019-10-04 13:38:38 -07003371 synchronized (mGlobalLock) {
Evan Rosky226de132020-01-03 18:00:29 -08003372 int effects = 0;
3373 deferWindowLayout();
3374 try {
3375 ArraySet<WindowContainer> haveConfigChanges = new ArraySet<>();
3376 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3377 t.getChanges().entrySet().iterator();
3378 while (entries.hasNext()) {
3379 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3380 entries.next();
Evan Roskya80f11c2020-01-23 19:17:10 -08003381 final WindowContainer wc = WindowContainer.RemoteToken.fromBinder(
3382 entry.getKey()).getContainer();
3383 int containerEffect = applyWindowContainerChange(wc, entry.getValue());
Evan Rosky226de132020-01-03 18:00:29 -08003384 effects |= containerEffect;
3385 // Lifecycle changes will trigger ensureConfig for everything.
3386 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) == 0
3387 && (containerEffect & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
Evan Roskya80f11c2020-01-23 19:17:10 -08003388 haveConfigChanges.add(wc);
Evan Rosky226de132020-01-03 18:00:29 -08003389 }
3390 }
3391 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) != 0) {
3392 // Already calls ensureActivityConfig
3393 mRootWindowContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
3394 } else if ((effects & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
3395 final PooledConsumer f = PooledLambda.obtainConsumer(
3396 ActivityRecord::ensureActivityConfiguration,
3397 PooledLambda.__(ActivityRecord.class), 0,
3398 false /* preserveWindow */);
3399 try {
3400 for (int i = haveConfigChanges.size() - 1; i >= 0; --i) {
3401 haveConfigChanges.valueAt(i).forAllActivities(f);
3402 }
3403 } finally {
3404 f.recycle();
3405 }
3406 }
3407 } finally {
3408 continueWindowLayout();
Evan Roskyddedfd42019-10-04 13:38:38 -07003409 }
3410 }
3411 } finally {
3412 Binder.restoreCallingIdentity(ident);
3413 }
3414 }
3415
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 @Override
3417 public boolean releaseActivityInstance(IBinder token) {
3418 synchronized (mGlobalLock) {
3419 final long origId = Binder.clearCallingIdentity();
3420 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003421 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3422 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 return false;
3424 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003425 r.destroyImmediately(true /* removeFromApp */, "app-req");
3426 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 } finally {
3428 Binder.restoreCallingIdentity(origId);
3429 }
3430 }
3431 }
3432
3433 @Override
3434 public void releaseSomeActivities(IApplicationThread appInt) {
3435 synchronized (mGlobalLock) {
3436 final long origId = Binder.clearCallingIdentity();
3437 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003438 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003439 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 } finally {
3441 Binder.restoreCallingIdentity(origId);
3442 }
3443 }
3444 }
3445
3446 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003447 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003448 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449 != PackageManager.PERMISSION_GRANTED) {
3450 throw new SecurityException("Requires permission "
3451 + android.Manifest.permission.DEVICE_POWER);
3452 }
3453
3454 synchronized (mGlobalLock) {
3455 long ident = Binder.clearCallingIdentity();
3456 if (mKeyguardShown != keyguardShowing) {
3457 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003458 final Message msg = PooledLambda.obtainMessage(
3459 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3460 keyguardShowing);
3461 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 }
3463 try {
wilsonshih177261f2019-02-22 12:02:18 +08003464 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 } finally {
3466 Binder.restoreCallingIdentity(ident);
3467 }
3468 }
3469
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003470 mH.post(() -> {
3471 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3472 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3473 }
3474 });
3475 }
3476
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003477 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003478 mH.post(() -> {
3479 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3480 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3481 }
3482 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 }
3484
3485 @Override
3486 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003487 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3488 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003489
3490 final File passedIconFile = new File(filePath);
3491 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3492 passedIconFile.getName());
3493 if (!legitIconFile.getPath().equals(filePath)
3494 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3495 throw new IllegalArgumentException("Bad file path: " + filePath
3496 + " passed for userId " + userId);
3497 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003498 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003499 }
3500
3501 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003503 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003504 synchronized (mGlobalLock) {
3505 final long ident = Binder.clearCallingIdentity();
3506 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003507 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 if (stack == null) {
3509 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3510 return;
3511 }
3512 if (!stack.isActivityTypeStandardOrUndefined()) {
3513 throw new IllegalArgumentException(
3514 "Removing non-standard stack is not allowed.");
3515 }
3516 mStackSupervisor.removeStack(stack);
3517 } finally {
3518 Binder.restoreCallingIdentity(ident);
3519 }
3520 }
3521 }
3522
3523 @Override
3524 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003525 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526
3527 synchronized (mGlobalLock) {
3528 final long ident = Binder.clearCallingIdentity();
3529 try {
3530 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3531 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003532 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003533 } finally {
3534 Binder.restoreCallingIdentity(ident);
3535 }
3536 }
3537 }
3538
3539 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003540 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003541 synchronized (mGlobalLock) {
3542 long ident = Binder.clearCallingIdentity();
3543 try {
3544 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3545 if (r == null) {
3546 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003547 "toggleFreeformWindowingMode: No activity record matching token="
3548 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003549 }
3550
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003551 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003552 if (stack == null) {
3553 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3554 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 }
3556
Yunfan Chend967af82019-01-17 18:30:18 +09003557 if (!stack.inFreeformWindowingMode()
3558 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3559 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3560 + "toggle between fullscreen and freeform.");
3561 }
3562
3563 if (stack.inFreeformWindowingMode()) {
3564 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003565 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003566 throw new IllegalStateException("Size-compat windows are currently not"
3567 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003568 } else if (stack.getParent().inFreeformWindowingMode()) {
3569 // If the window is on a freeform display, set it to undefined. It will be
3570 // resolved to freeform and it can adjust windowing mode when the display mode
3571 // changes in runtime.
3572 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003573 } else {
3574 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3575 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003576 } finally {
3577 Binder.restoreCallingIdentity(ident);
3578 }
3579 }
3580 }
3581
3582 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3583 @Override
3584 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003585 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003586 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003587 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003588 }
3589
3590 /** Unregister a task stack listener so that it stops receiving callbacks. */
3591 @Override
3592 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003593 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003595 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003596 }
3597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 @Override
3599 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3600 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3601 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3602 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3603 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3604 }
3605
3606 @Override
3607 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3608 IBinder activityToken, int flags) {
3609 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3610 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3611 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3612 }
3613
3614 @Override
3615 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3616 Bundle args) {
3617 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3618 true /* focused */, true /* newSessionId */, userHandle, args,
3619 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3620 }
3621
3622 @Override
3623 public Bundle getAssistContextExtras(int requestType) {
3624 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3625 null, null, true /* focused */, true /* newSessionId */,
3626 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3627 if (pae == null) {
3628 return null;
3629 }
3630 synchronized (pae) {
3631 while (!pae.haveResult) {
3632 try {
3633 pae.wait();
3634 } catch (InterruptedException e) {
3635 }
3636 }
3637 }
3638 synchronized (mGlobalLock) {
3639 buildAssistBundleLocked(pae, pae.result);
3640 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003641 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003642 }
3643 return pae.extras;
3644 }
3645
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003646 /**
3647 * Binder IPC calls go through the public entry point.
3648 * This can be called with or without the global lock held.
3649 */
3650 private static int checkCallingPermission(String permission) {
3651 return checkPermission(
3652 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3653 }
3654
3655 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003656 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003657 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3658 mAmInternal.enforceCallingPermission(permission, func);
3659 }
3660 }
3661
3662 @VisibleForTesting
3663 int checkGetTasksPermission(String permission, int pid, int uid) {
3664 return checkPermission(permission, pid, uid);
3665 }
3666
3667 static int checkPermission(String permission, int pid, int uid) {
3668 if (permission == null) {
3669 return PackageManager.PERMISSION_DENIED;
3670 }
3671 return checkComponentPermission(permission, pid, uid, -1, true);
3672 }
3673
Wale Ogunwale214f3482018-10-04 11:00:47 -07003674 public static int checkComponentPermission(String permission, int pid, int uid,
3675 int owningUid, boolean exported) {
3676 return ActivityManagerService.checkComponentPermission(
3677 permission, pid, uid, owningUid, exported);
3678 }
3679
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003680 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3681 if (getRecentTasks().isCallerRecents(callingUid)) {
3682 // Always allow the recents component to get tasks
3683 return true;
3684 }
3685
3686 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3687 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3688 if (!allowed) {
3689 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3690 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3691 // Temporary compatibility: some existing apps on the system image may
3692 // still be requesting the old permission and not switched to the new
3693 // one; if so, we'll still allow them full access. This means we need
3694 // to see if they are holding the old permission and are a system app.
3695 try {
3696 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3697 allowed = true;
3698 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3699 + " is using old GET_TASKS but privileged; allowing");
3700 }
3701 } catch (RemoteException e) {
3702 }
3703 }
3704 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3705 + " does not hold REAL_GET_TASKS; limiting output");
3706 }
3707 return allowed;
3708 }
3709
Nicholas Sauer0259e532019-08-30 08:24:55 -07003710 boolean isCrossUserAllowed(int pid, int uid) {
3711 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3712 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3713 }
3714
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3716 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3717 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3718 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003719 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003720 "enqueueAssistContext()");
3721
3722 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003723 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003724 if (activity == null) {
3725 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3726 return null;
3727 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003728 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3730 return null;
3731 }
3732 if (focused) {
3733 if (activityToken != null) {
3734 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3735 if (activity != caller) {
3736 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3737 + " is not current top " + activity);
3738 return null;
3739 }
3740 }
3741 } else {
3742 activity = ActivityRecord.forTokenLocked(activityToken);
3743 if (activity == null) {
3744 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3745 + " couldn't be found");
3746 return null;
3747 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003748 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3750 return null;
3751 }
3752 }
3753
3754 PendingAssistExtras pae;
3755 Bundle extras = new Bundle();
3756 if (args != null) {
3757 extras.putAll(args);
3758 }
3759 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003760 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003761
3762 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3763 userHandle);
3764 pae.isHome = activity.isActivityTypeHome();
3765
3766 // Increment the sessionId if necessary
3767 if (newSessionId) {
3768 mViSessionId++;
3769 }
3770 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003771 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3772 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003773 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003774 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003775 } catch (RemoteException e) {
3776 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3777 return null;
3778 }
3779 return pae;
3780 }
3781 }
3782
3783 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3784 if (result != null) {
3785 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3786 }
3787 if (pae.hint != null) {
3788 pae.extras.putBoolean(pae.hint, true);
3789 }
3790 }
3791
3792 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3793 IAssistDataReceiver receiver;
3794 synchronized (mGlobalLock) {
3795 mPendingAssistExtras.remove(pae);
3796 receiver = pae.receiver;
3797 }
3798 if (receiver != null) {
3799 // Caller wants result sent back to them.
3800 Bundle sendBundle = new Bundle();
3801 // At least return the receiver extras
3802 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3803 try {
3804 pae.receiver.onHandleAssistData(sendBundle);
3805 } catch (RemoteException e) {
3806 }
3807 }
3808 }
3809
3810 public class PendingAssistExtras extends Binder implements Runnable {
3811 public final ActivityRecord activity;
3812 public boolean isHome;
3813 public final Bundle extras;
3814 public final Intent intent;
3815 public final String hint;
3816 public final IAssistDataReceiver receiver;
3817 public final int userHandle;
3818 public boolean haveResult = false;
3819 public Bundle result = null;
3820 public AssistStructure structure = null;
3821 public AssistContent content = null;
3822 public Bundle receiverExtras;
3823
3824 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3825 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3826 int _userHandle) {
3827 activity = _activity;
3828 extras = _extras;
3829 intent = _intent;
3830 hint = _hint;
3831 receiver = _receiver;
3832 receiverExtras = _receiverExtras;
3833 userHandle = _userHandle;
3834 }
3835
3836 @Override
3837 public void run() {
3838 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3839 synchronized (this) {
3840 haveResult = true;
3841 notifyAll();
3842 }
3843 pendingAssistExtrasTimedOut(this);
3844 }
3845 }
3846
3847 @Override
3848 public boolean isAssistDataAllowedOnCurrentActivity() {
3849 int userId;
3850 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003851 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003852 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3853 return false;
3854 }
3855
Wale Ogunwale21e06482019-11-18 05:14:15 -08003856 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003857 if (activity == null) {
3858 return false;
3859 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003860 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003861 }
3862 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3863 }
3864
3865 @Override
3866 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3867 long ident = Binder.clearCallingIdentity();
3868 try {
3869 synchronized (mGlobalLock) {
3870 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003871 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 if (top != caller) {
3873 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3874 + " is not current top " + top);
3875 return false;
3876 }
3877 if (!top.nowVisible) {
3878 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3879 + " is not visible");
3880 return false;
3881 }
3882 }
3883 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3884 token);
3885 } finally {
3886 Binder.restoreCallingIdentity(ident);
3887 }
3888 }
3889
3890 @Override
3891 public boolean isRootVoiceInteraction(IBinder token) {
3892 synchronized (mGlobalLock) {
3893 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3894 if (r == null) {
3895 return false;
3896 }
3897 return r.rootVoiceInteraction;
3898 }
3899 }
3900
Wale Ogunwalef6733932018-06-27 05:14:34 -07003901 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3902 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3903 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3904 if (activityToCallback == null) return;
3905 activityToCallback.setVoiceSessionLocked(voiceSession);
3906
3907 // Inform the activity
3908 try {
3909 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3910 voiceInteractor);
3911 long token = Binder.clearCallingIdentity();
3912 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003913 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003914 } finally {
3915 Binder.restoreCallingIdentity(token);
3916 }
3917 // TODO: VI Should we cache the activity so that it's easier to find later
3918 // rather than scan through all the stacks and activities?
3919 } catch (RemoteException re) {
3920 activityToCallback.clearVoiceSessionLocked();
3921 // TODO: VI Should this terminate the voice session?
3922 }
3923 }
3924
3925 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3926 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3927 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3928 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3929 boolean wasRunningVoice = mRunningVoice != null;
3930 mRunningVoice = session;
3931 if (!wasRunningVoice) {
3932 mVoiceWakeLock.acquire();
3933 updateSleepIfNeededLocked();
3934 }
3935 }
3936 }
3937
3938 void finishRunningVoiceLocked() {
3939 if (mRunningVoice != null) {
3940 mRunningVoice = null;
3941 mVoiceWakeLock.release();
3942 updateSleepIfNeededLocked();
3943 }
3944 }
3945
3946 @Override
3947 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3948 synchronized (mGlobalLock) {
3949 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3950 if (keepAwake) {
3951 mVoiceWakeLock.acquire();
3952 } else {
3953 mVoiceWakeLock.release();
3954 }
3955 }
3956 }
3957 }
3958
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 @Override
3960 public ComponentName getActivityClassForToken(IBinder token) {
3961 synchronized (mGlobalLock) {
3962 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3963 if (r == null) {
3964 return null;
3965 }
3966 return r.intent.getComponent();
3967 }
3968 }
3969
3970 @Override
3971 public String getPackageForToken(IBinder token) {
3972 synchronized (mGlobalLock) {
3973 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3974 if (r == null) {
3975 return null;
3976 }
3977 return r.packageName;
3978 }
3979 }
3980
3981 @Override
3982 public void showLockTaskEscapeMessage(IBinder token) {
3983 synchronized (mGlobalLock) {
3984 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3985 if (r == null) {
3986 return;
3987 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003988 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 }
3990 }
3991
3992 @Override
3993 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003994 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 final long token = Binder.clearCallingIdentity();
3996 try {
3997 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003998 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 }
4000 } finally {
4001 Binder.restoreCallingIdentity(token);
4002 }
4003 }
4004
4005 /**
4006 * Try to place task to provided position. The final position might be different depending on
4007 * current user and stacks state. The task will be moved to target stack if it's currently in
4008 * different stack.
4009 */
4010 @Override
4011 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 synchronized (mGlobalLock) {
4014 long ident = Binder.clearCallingIdentity();
4015 try {
4016 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
4017 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08004018 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 if (task == null) {
4020 throw new IllegalArgumentException("positionTaskInStack: no task for id="
4021 + taskId);
4022 }
4023
Louis Chang149d5c82019-12-30 09:47:39 +08004024 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025
4026 if (stack == null) {
4027 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
4028 + stackId);
4029 }
4030 if (!stack.isActivityTypeStandardOrUndefined()) {
4031 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
4032 + " the position of task " + taskId + " in/to non-standard stack");
4033 }
4034
4035 // TODO: Have the callers of this API call a separate reparent method if that is
4036 // what they intended to do vs. having this method also do reparenting.
4037 if (task.getStack() == stack) {
4038 // Change position in current stack.
4039 stack.positionChildAt(task, position);
4040 } else {
4041 // Reparent to new stack.
4042 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4043 !DEFER_RESUME, "positionTaskInStack");
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(ident);
4047 }
4048 }
4049 }
4050
4051 @Override
4052 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4053 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4054 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004055 + Arrays.toString(horizontalSizeConfiguration) + " "
4056 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 synchronized (mGlobalLock) {
4058 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4059 if (record == null) {
4060 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4061 + "found for: " + token);
4062 }
4063 record.setSizeConfigurations(horizontalSizeConfiguration,
4064 verticalSizeConfigurations, smallestSizeConfigurations);
4065 }
4066 }
4067
4068 /**
4069 * Dismisses split-screen multi-window mode.
4070 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4071 */
4072 @Override
4073 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004074 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4076 final long ident = Binder.clearCallingIdentity();
4077 try {
4078 synchronized (mGlobalLock) {
4079 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004080 mRootWindowContainer.getDefaultDisplay().getRootSplitScreenPrimaryTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 if (stack == null) {
4082 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4083 return;
4084 }
4085
4086 if (toTop) {
4087 // Caller wants the current split-screen primary stack to be the top stack after
4088 // it goes fullscreen, so move it to the front.
4089 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004090 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004092 // stack after it goes fullscreen, so we move the focus to the top-most
4093 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4095 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4096 if (otherStack != null) {
4097 otherStack.moveToFront("dismissSplitScreenMode_other");
4098 }
4099 }
4100
Evan Rosky10475742018-09-05 19:02:48 -07004101 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004102 }
4103 } finally {
4104 Binder.restoreCallingIdentity(ident);
4105 }
4106 }
4107
4108 /**
4109 * Dismisses Pip
4110 * @param animate True if the dismissal should be animated.
4111 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4112 * default animation duration should be used.
4113 */
4114 @Override
4115 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004116 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 final long ident = Binder.clearCallingIdentity();
4118 try {
4119 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004120 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004121 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 if (stack == null) {
4123 Slog.w(TAG, "dismissPip: pinned stack not found.");
4124 return;
4125 }
4126 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4127 throw new IllegalArgumentException("Stack: " + stack
4128 + " doesn't support animated resize.");
4129 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004130 /**
4131 * TODO(b/146594635): Remove all PIP animation code from WM
4132 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4133 */
4134 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004135 stack.animateResizePinnedStack(null /* destBounds */,
4136 null /* sourceHintBounds */, animationDuration,
4137 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004139 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 }
4141 }
4142 } finally {
4143 Binder.restoreCallingIdentity(ident);
4144 }
4145 }
4146
4147 @Override
4148 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004149 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004150 synchronized (mGlobalLock) {
4151 mSuppressResizeConfigChanges = suppress;
4152 }
4153 }
4154
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004155 @Override
4156 // TODO: API should just be about changing windowing modes...
4157 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 "moveTasksToFullscreenStack()");
4160 synchronized (mGlobalLock) {
4161 final long origId = Binder.clearCallingIdentity();
4162 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004163 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 if (stack != null){
4165 if (!stack.isActivityTypeStandardOrUndefined()) {
4166 throw new IllegalArgumentException(
4167 "You can't move tasks from non-standard stacks.");
4168 }
4169 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4170 }
4171 } finally {
4172 Binder.restoreCallingIdentity(origId);
4173 }
4174 }
4175 }
4176
4177 /**
4178 * Moves the top activity in the input stackId to the pinned stack.
4179 *
4180 * @param stackId Id of stack to move the top activity to pinned stack.
4181 * @param bounds Bounds to use for pinned stack.
4182 *
4183 * @return True if the top activity of the input stack was successfully moved to the pinned
4184 * stack.
4185 */
4186 @Override
4187 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 "moveTopActivityToPinnedStack()");
4190 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4193 + "Device doesn't support picture-in-picture mode");
4194 }
4195
4196 long ident = Binder.clearCallingIdentity();
4197 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004198 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004199 } finally {
4200 Binder.restoreCallingIdentity(ident);
4201 }
4202 }
4203 }
4204
4205 @Override
4206 public boolean isInMultiWindowMode(IBinder token) {
4207 final long origId = Binder.clearCallingIdentity();
4208 try {
4209 synchronized (mGlobalLock) {
4210 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4211 if (r == null) {
4212 return false;
4213 }
4214 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4215 return r.inMultiWindowMode();
4216 }
4217 } finally {
4218 Binder.restoreCallingIdentity(origId);
4219 }
4220 }
4221
4222 @Override
4223 public boolean isInPictureInPictureMode(IBinder token) {
4224 final long origId = Binder.clearCallingIdentity();
4225 try {
4226 synchronized (mGlobalLock) {
4227 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4228 }
4229 } finally {
4230 Binder.restoreCallingIdentity(origId);
4231 }
4232 }
4233
4234 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004235 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4236 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 return false;
4238 }
4239
4240 // If we are animating to fullscreen then we have already dispatched the PIP mode
4241 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004242 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004243 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 }
4245
4246 @Override
4247 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4248 final long origId = Binder.clearCallingIdentity();
4249 try {
4250 synchronized (mGlobalLock) {
4251 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4252 "enterPictureInPictureMode", token, params);
4253
4254 // If the activity is already in picture in picture mode, then just return early
4255 if (isInPictureInPictureMode(r)) {
4256 return true;
4257 }
4258
4259 // Activity supports picture-in-picture, now check that we can enter PiP at this
4260 // point, if it is
4261 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4262 false /* beforeStopping */)) {
4263 return false;
4264 }
4265
4266 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004267 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004268 if (r.getParent() == null) {
4269 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4270 return;
4271 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004272 // Only update the saved args from the args that are set
4273 r.pictureInPictureArgs.copyOnlySet(params);
4274 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4275 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4276 // Adjust the source bounds by the insets for the transition down
4277 final Rect sourceBounds = new Rect(
4278 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004279 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004280 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004281 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004282 stack.setPictureInPictureAspectRatio(aspectRatio);
4283 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004284 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4285 r.info.applicationInfo.uid, r.shortComponentName,
4286 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004287 logPictureInPictureArgs(params);
4288 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 };
4290
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004291 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 // If the keyguard is showing or occluded, then try and dismiss it before
4293 // entering picture-in-picture (this will prompt the user to authenticate if the
4294 // device is currently locked).
4295 dismissKeyguard(token, new KeyguardDismissCallback() {
4296 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 public void onDismissSucceeded() {
4298 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
4300 }, null /* message */);
4301 } else {
4302 // Enter picture in picture immediately otherwise
4303 enterPipRunnable.run();
4304 }
4305 return true;
4306 }
4307 } finally {
4308 Binder.restoreCallingIdentity(origId);
4309 }
4310 }
4311
4312 @Override
4313 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4314 final long origId = Binder.clearCallingIdentity();
4315 try {
4316 synchronized (mGlobalLock) {
4317 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4318 "setPictureInPictureParams", token, params);
4319
4320 // Only update the saved args from the args that are set
4321 r.pictureInPictureArgs.copyOnlySet(params);
4322 if (r.inPinnedWindowingMode()) {
4323 // If the activity is already in picture-in-picture, update the pinned stack now
4324 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4325 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004326 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 if (!stack.isAnimatingBoundsToFullscreen()) {
4328 stack.setPictureInPictureAspectRatio(
4329 r.pictureInPictureArgs.getAspectRatio());
4330 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4331 }
4332 }
4333 logPictureInPictureArgs(params);
4334 }
4335 } finally {
4336 Binder.restoreCallingIdentity(origId);
4337 }
4338 }
4339
4340 @Override
4341 public int getMaxNumPictureInPictureActions(IBinder token) {
4342 // Currently, this is a static constant, but later, we may change this to be dependent on
4343 // the context of the activity
4344 return 3;
4345 }
4346
4347 private void logPictureInPictureArgs(PictureInPictureParams params) {
4348 if (params.hasSetActions()) {
4349 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4350 params.getActions().size());
4351 }
4352 if (params.hasSetAspectRatio()) {
4353 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4354 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4355 MetricsLogger.action(lm);
4356 }
4357 }
4358
4359 /**
4360 * Checks the state of the system and the activity associated with the given {@param token} to
4361 * verify that picture-in-picture is supported for that activity.
4362 *
4363 * @return the activity record for the given {@param token} if all the checks pass.
4364 */
4365 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4366 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 throw new IllegalStateException(caller
4369 + ": Device doesn't support picture-in-picture mode.");
4370 }
4371
4372 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4373 if (r == null) {
4374 throw new IllegalStateException(caller
4375 + ": Can't find activity for token=" + token);
4376 }
4377
4378 if (!r.supportsPictureInPicture()) {
4379 throw new IllegalStateException(caller
4380 + ": Current activity does not support picture-in-picture.");
4381 }
4382
4383 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004384 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004385 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 final float minAspectRatio = mContext.getResources().getFloat(
4387 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4388 final float maxAspectRatio = mContext.getResources().getFloat(
4389 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4390 throw new IllegalArgumentException(String.format(caller
4391 + ": Aspect ratio is too extreme (must be between %f and %f).",
4392 minAspectRatio, maxAspectRatio));
4393 }
4394
4395 // Truncate the number of actions if necessary
4396 params.truncateActions(getMaxNumPictureInPictureActions(token));
4397
4398 return r;
4399 }
4400
4401 @Override
4402 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004403 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 synchronized (mGlobalLock) {
4405 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4406 if (r == null) {
4407 throw new IllegalArgumentException("Activity does not exist; token="
4408 + activityToken);
4409 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004410 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004411 }
4412 }
4413
4414 @Override
4415 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4416 Rect tempDockedTaskInsetBounds,
4417 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004418 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 long ident = Binder.clearCallingIdentity();
4420 try {
4421 synchronized (mGlobalLock) {
4422 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4423 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4424 PRESERVE_WINDOWS);
4425 }
4426 } finally {
4427 Binder.restoreCallingIdentity(ident);
4428 }
4429 }
4430
4431 @Override
4432 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004433 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004434 final long ident = Binder.clearCallingIdentity();
4435 try {
4436 synchronized (mGlobalLock) {
4437 mStackSupervisor.setSplitScreenResizing(resizing);
4438 }
4439 } finally {
4440 Binder.restoreCallingIdentity(ident);
4441 }
4442 }
4443
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 /**
4445 * Check that we have the features required for VR-related API calls, and throw an exception if
4446 * not.
4447 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004448 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004449 if (!mContext.getPackageManager().hasSystemFeature(
4450 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4451 throw new UnsupportedOperationException("VR mode not supported on this device!");
4452 }
4453 }
4454
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 @Override
4456 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458
4459 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4460
4461 ActivityRecord r;
4462 synchronized (mGlobalLock) {
4463 r = ActivityRecord.isInStackLocked(token);
4464 }
4465
4466 if (r == null) {
4467 throw new IllegalArgumentException();
4468 }
4469
4470 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004471 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 VrManagerInternal.NO_ERROR) {
4473 return err;
4474 }
4475
4476 // Clear the binder calling uid since this path may call moveToTask().
4477 final long callingId = Binder.clearCallingIdentity();
4478 try {
4479 synchronized (mGlobalLock) {
4480 r.requestedVrComponent = (enabled) ? packageName : null;
4481
4482 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004483 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004484 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 }
4486 return 0;
4487 }
4488 } finally {
4489 Binder.restoreCallingIdentity(callingId);
4490 }
4491 }
4492
4493 @Override
4494 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4495 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4496 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004497 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004498 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4499 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4500 }
Louis Changcdec0802019-11-11 11:45:07 +08004501 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 || activity.voiceSession != null) {
4503 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4504 return;
4505 }
4506 if (activity.pendingVoiceInteractionStart) {
4507 Slog.w(TAG, "Pending start of voice interaction already.");
4508 return;
4509 }
4510 activity.pendingVoiceInteractionStart = true;
4511 }
4512 LocalServices.getService(VoiceInteractionManagerInternal.class)
4513 .startLocalVoiceInteraction(callingActivity, options);
4514 }
4515
4516 @Override
4517 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4518 LocalServices.getService(VoiceInteractionManagerInternal.class)
4519 .stopLocalVoiceInteraction(callingActivity);
4520 }
4521
4522 @Override
4523 public boolean supportsLocalVoiceInteraction() {
4524 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4525 .supportsLocalVoiceInteraction();
4526 }
4527
4528 /** Notifies all listeners when the pinned stack animation starts. */
4529 @Override
4530 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004531 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004532 }
4533
4534 /** Notifies all listeners when the pinned stack animation ends. */
4535 @Override
4536 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004537 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 }
4539
4540 @Override
4541 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004542 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 final long ident = Binder.clearCallingIdentity();
4544 try {
4545 synchronized (mGlobalLock) {
4546 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4547 }
4548 } finally {
4549 Binder.restoreCallingIdentity(ident);
4550 }
4551 }
4552
4553 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004554 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004555 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004556
4557 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004558 if (mWindowManager == null) {
4559 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4560 return false;
4561 }
4562
4563 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004564 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004565 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004566 }
4567
Riddle Hsua0022cd2019-09-09 21:12:41 +08004568 mH.sendMessage(PooledLambda.obtainMessage(
4569 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4570 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571
4572 final long origId = Binder.clearCallingIdentity();
4573 try {
4574 if (values != null) {
4575 Settings.System.clearConfiguration(values);
4576 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004577 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004578 UserHandle.USER_NULL, false /* deferResume */,
4579 mTmpUpdateConfigurationResult);
4580 return mTmpUpdateConfigurationResult.changes != 0;
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
4588 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4589 CharSequence message) {
4590 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004591 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004592 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4593 }
4594 final long callingId = Binder.clearCallingIdentity();
4595 try {
4596 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004597 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004598 }
4599 } finally {
4600 Binder.restoreCallingIdentity(callingId);
4601 }
4602 }
4603
4604 @Override
4605 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004606 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004607 "cancelTaskWindowTransition()");
4608 final long ident = Binder.clearCallingIdentity();
4609 try {
4610 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004611 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004612 MATCH_TASK_IN_STACKS_ONLY);
4613 if (task == null) {
4614 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4615 return;
4616 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004617 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004618 }
4619 } finally {
4620 Binder.restoreCallingIdentity(ident);
4621 }
4622 }
4623
4624 @Override
4625 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004626 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004627 final long ident = Binder.clearCallingIdentity();
4628 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004629 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 } finally {
4631 Binder.restoreCallingIdentity(ident);
4632 }
4633 }
4634
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004635 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4636 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004637 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004638 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004639 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004640 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4641 if (task == null) {
4642 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4643 return null;
4644 }
4645 }
4646 // Don't call this while holding the lock as this operation might hit the disk.
4647 return task.getSnapshot(reducedResolution, restoreFromDisk);
4648 }
4649
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004650 @Override
4651 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4652 synchronized (mGlobalLock) {
4653 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4654 if (r == null) {
4655 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4656 + token);
4657 return;
4658 }
4659 final long origId = Binder.clearCallingIdentity();
4660 try {
4661 r.setDisablePreviewScreenshots(disable);
4662 } finally {
4663 Binder.restoreCallingIdentity(origId);
4664 }
4665 }
4666 }
4667
Riddle Hsu440f88b2019-11-06 22:17:35 +08004668 @Override
4669 public void invalidateHomeTaskSnapshot(IBinder token) {
4670 synchronized (mGlobalLock) {
4671 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4672 if (r == null || !r.isActivityTypeHome()) {
4673 return;
4674 }
4675 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4676 }
4677 }
4678
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004679 /** Return the user id of the last resumed activity. */
4680 @Override
4681 public @UserIdInt
4682 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004683 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004684 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4685 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004686 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004688 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004689 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004690 }
4691 }
4692
4693 @Override
4694 public void updateLockTaskFeatures(int userId, int flags) {
4695 final int callingUid = Binder.getCallingUid();
4696 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004697 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004698 "updateLockTaskFeatures()");
4699 }
4700 synchronized (mGlobalLock) {
4701 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4702 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004703 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004704 }
4705 }
4706
4707 @Override
4708 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4709 synchronized (mGlobalLock) {
4710 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4711 if (r == null) {
4712 return;
4713 }
4714 final long origId = Binder.clearCallingIdentity();
4715 try {
4716 r.setShowWhenLocked(showWhenLocked);
4717 } finally {
4718 Binder.restoreCallingIdentity(origId);
4719 }
4720 }
4721 }
4722
4723 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004724 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4725 synchronized (mGlobalLock) {
4726 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4727 if (r == null) {
4728 return;
4729 }
4730 final long origId = Binder.clearCallingIdentity();
4731 try {
4732 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4733 } finally {
4734 Binder.restoreCallingIdentity(origId);
4735 }
4736 }
4737 }
4738
4739 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004740 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4741 synchronized (mGlobalLock) {
4742 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4743 if (r == null) {
4744 return;
4745 }
4746 final long origId = Binder.clearCallingIdentity();
4747 try {
4748 r.setTurnScreenOn(turnScreenOn);
4749 } finally {
4750 Binder.restoreCallingIdentity(origId);
4751 }
4752 }
4753 }
4754
4755 @Override
4756 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004758 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004759 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004760 synchronized (mGlobalLock) {
4761 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4762 if (r == null) {
4763 return;
4764 }
4765 final long origId = Binder.clearCallingIdentity();
4766 try {
4767 r.registerRemoteAnimations(definition);
4768 } finally {
4769 Binder.restoreCallingIdentity(origId);
4770 }
4771 }
4772 }
4773
4774 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004775 public void unregisterRemoteAnimations(IBinder token) {
4776 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4777 "unregisterRemoteAnimations");
4778 synchronized (mGlobalLock) {
4779 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4780 if (r == null) {
4781 return;
4782 }
4783 final long origId = Binder.clearCallingIdentity();
4784 try {
4785 r.unregisterRemoteAnimations();
4786 } finally {
4787 Binder.restoreCallingIdentity(origId);
4788 }
4789 }
4790 }
4791
4792 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004793 public void registerRemoteAnimationForNextActivityStart(String packageName,
4794 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004795 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004796 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004797 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004798 synchronized (mGlobalLock) {
4799 final long origId = Binder.clearCallingIdentity();
4800 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004801 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004802 packageName, adapter);
4803 } finally {
4804 Binder.restoreCallingIdentity(origId);
4805 }
4806 }
4807 }
4808
Evan Rosky966759f2019-01-15 10:33:58 -08004809 @Override
4810 public void registerRemoteAnimationsForDisplay(int displayId,
4811 RemoteAnimationDefinition definition) {
4812 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4813 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004814 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004815 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004816 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004817 if (display == null) {
4818 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4819 return;
4820 }
4821 final long origId = Binder.clearCallingIdentity();
4822 try {
4823 display.mDisplayContent.registerRemoteAnimations(definition);
4824 } finally {
4825 Binder.restoreCallingIdentity(origId);
4826 }
4827 }
4828 }
4829
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004830 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4831 @Override
4832 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4833 synchronized (mGlobalLock) {
4834 final long origId = Binder.clearCallingIdentity();
4835 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004836 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004837 } finally {
4838 Binder.restoreCallingIdentity(origId);
4839 }
4840 }
4841 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004842
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004843 @Override
4844 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004845 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004846 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004847 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004848 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004849 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004850 }
4851 }
4852
4853 @Override
4854 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004855 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004856 != PERMISSION_GRANTED) {
4857 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4858 + Binder.getCallingPid()
4859 + ", uid=" + Binder.getCallingUid()
4860 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4861 Slog.w(TAG, msg);
4862 throw new SecurityException(msg);
4863 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004864 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004865 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004866 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004867 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004868 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004869 }
4870 }
4871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004872 @Override
4873 public void stopAppSwitches() {
4874 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4875 synchronized (mGlobalLock) {
4876 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004877 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004878 mDidAppSwitch = false;
4879 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4880 }
4881 }
4882
4883 @Override
4884 public void resumeAppSwitches() {
4885 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4886 synchronized (mGlobalLock) {
4887 // Note that we don't execute any pending app switches... we will
4888 // let those wait until either the timeout, or the next start
4889 // activity request.
4890 mAppSwitchesAllowedTime = 0;
4891 }
4892 }
4893
Ricky Wai906af482019-06-03 17:25:28 +01004894 long getLastStopAppSwitchesTime() {
4895 return mLastStopAppSwitchesTime;
4896 }
4897
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004898 void onStartActivitySetDidAppSwitch() {
4899 if (mDidAppSwitch) {
4900 // This is the second allowed switch since we stopped switches, so now just generally
4901 // allow switches. Use case:
4902 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4903 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4904 // anyone to switch again).
4905 mAppSwitchesAllowedTime = 0;
4906 } else {
4907 mDidAppSwitch = true;
4908 }
4909 }
4910
4911 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004912 boolean shouldDisableNonVrUiLocked() {
4913 return mVrController.shouldDisableNonVrUiLocked();
4914 }
4915
Wale Ogunwale53783742018-09-16 10:21:51 -07004916 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004917 // 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 +00004918 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004919 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004920 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4921 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004922 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004923 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004924 }
4925 mH.post(() -> {
4926 if (!mVrController.onVrModeChanged(r)) {
4927 return;
4928 }
4929 synchronized (mGlobalLock) {
4930 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4931 mWindowManager.disableNonVrUi(disableNonVrUi);
4932 if (disableNonVrUi) {
4933 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4934 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004935 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004936 }
4937 }
4938 });
4939 }
4940
Wale Ogunwale53783742018-09-16 10:21:51 -07004941 @Override
4942 public int getPackageScreenCompatMode(String packageName) {
4943 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4944 synchronized (mGlobalLock) {
4945 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4946 }
4947 }
4948
4949 @Override
4950 public void setPackageScreenCompatMode(String packageName, int mode) {
4951 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4952 "setPackageScreenCompatMode");
4953 synchronized (mGlobalLock) {
4954 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4955 }
4956 }
4957
4958 @Override
4959 public boolean getPackageAskScreenCompat(String packageName) {
4960 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4961 synchronized (mGlobalLock) {
4962 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4963 }
4964 }
4965
4966 @Override
4967 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4968 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4969 "setPackageAskScreenCompat");
4970 synchronized (mGlobalLock) {
4971 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4972 }
4973 }
4974
Wale Ogunwale64258362018-10-16 15:13:37 -07004975 public static String relaunchReasonToString(int relaunchReason) {
4976 switch (relaunchReason) {
4977 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4978 return "window_resize";
4979 case RELAUNCH_REASON_FREE_RESIZE:
4980 return "free_resize";
4981 default:
4982 return null;
4983 }
4984 }
4985
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004986 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004987 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004988 }
4989
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004990 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004991 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004992 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4993 }
4994
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004995 boolean isKeyguardLocked() {
4996 return mKeyguardController.isKeyguardLocked();
4997 }
4998
Garfield Tan01548632018-11-27 10:15:48 -08004999 /**
5000 * Clears launch params for the given package.
5001 * @param packageNames the names of the packages of which the launch params are to be cleared
5002 */
5003 @Override
5004 public void clearLaunchParamsForPackages(List<String> packageNames) {
5005 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5006 "clearLaunchParamsForPackages");
5007 synchronized (mGlobalLock) {
5008 for (int i = 0; i < packageNames.size(); ++i) {
5009 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
5010 }
5011 }
5012 }
5013
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005014 /**
5015 * Makes the display with the given id a single task instance display. I.e the display can only
5016 * contain one task.
5017 */
5018 @Override
5019 public void setDisplayToSingleTaskInstance(int displayId) {
5020 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5021 "setDisplayToSingleTaskInstance");
5022 final long origId = Binder.clearCallingIdentity();
5023 try {
Louis Chang677921f2019-12-06 16:44:24 +08005024 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08005025 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005026 if (display != null) {
5027 display.setDisplayToSingleTaskInstance();
5028 }
5029 } finally {
5030 Binder.restoreCallingIdentity(origId);
5031 }
5032 }
5033
jorgegil@google.com06bc3232019-10-31 14:51:22 -07005034 /**
5035 * Requests that an activity should enter picture-in-picture mode if possible.
5036 */
5037 @Override
5038 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
5039 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5040 "requestPictureInPictureMode");
5041 final long origId = Binder.clearCallingIdentity();
5042 try {
5043 synchronized (mGlobalLock) {
5044 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
5045 if (activity == null) {
5046 return;
5047 }
5048
5049 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
5050 "requestPictureInPictureMode", /* beforeStopping */ false);
5051 if (!canEnterPictureInPicture) {
5052 throw new IllegalStateException(
5053 "Requested PIP on an activity that doesn't support it");
5054 }
5055
5056 try {
5057 final ClientTransaction transaction = ClientTransaction.obtain(
5058 activity.app.getThread(),
5059 activity.token);
5060 transaction.addCallback(EnterPipRequestedItem.obtain());
5061 getLifecycleManager().scheduleTransaction(transaction);
5062 } catch (Exception e) {
5063 Slog.w(TAG, "Failed to send enter pip requested item: "
5064 + activity.intent.getComponent(), e);
5065 }
5066 }
5067 } finally {
5068 Binder.restoreCallingIdentity(origId);
5069 }
5070 }
5071
Wale Ogunwale31913b52018-10-13 08:29:31 -07005072 void dumpLastANRLocked(PrintWriter pw) {
5073 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5074 if (mLastANRState == null) {
5075 pw.println(" <no ANR has occurred since boot>");
5076 } else {
5077 pw.println(mLastANRState);
5078 }
5079 }
5080
5081 void dumpLastANRTracesLocked(PrintWriter pw) {
5082 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5083
5084 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5085 if (ArrayUtils.isEmpty(files)) {
5086 pw.println(" <no ANR has occurred since boot>");
5087 return;
5088 }
5089 // Find the latest file.
5090 File latest = null;
5091 for (File f : files) {
5092 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5093 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005094 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005095 }
5096 pw.print("File: ");
5097 pw.print(latest.getName());
5098 pw.println();
5099 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5100 String line;
5101 while ((line = in.readLine()) != null) {
5102 pw.println(line);
5103 }
5104 } catch (IOException e) {
5105 pw.print("Unable to read: ");
5106 pw.print(e);
5107 pw.println();
5108 }
5109 }
5110
5111 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5112 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5113 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5114 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5115 }
5116
5117 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5118 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5119 pw.println(header);
5120
Louis Chang149d5c82019-12-30 09:47:39 +08005121 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005122 dumpPackage);
5123 boolean needSep = printedAnything;
5124
5125 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005126 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005127 " ResumedActivity: ");
5128 if (printed) {
5129 printedAnything = true;
5130 needSep = false;
5131 }
5132
5133 if (dumpPackage == null) {
5134 if (needSep) {
5135 pw.println();
5136 }
5137 printedAnything = true;
5138 mStackSupervisor.dump(pw, " ");
5139 }
5140
5141 if (!printedAnything) {
5142 pw.println(" (nothing)");
5143 }
5144 }
5145
5146 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005147 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005148 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005149 pw.println(" ");
5150 }
5151
5152 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5153 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5154 getActivityStartController().dump(pw, "", dumpPackage);
5155 }
5156
5157 /**
5158 * There are three things that cmd can be:
5159 * - a flattened component name that matches an existing activity
5160 * - the cmd arg isn't the flattened component name of an existing activity:
5161 * dump all activity whose component contains the cmd as a substring
5162 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005163 * <p>
5164 * The caller should not hold lock when calling this method because it will wait for the
5165 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005166 *
5167 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5168 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5169 */
5170 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5171 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5172 ArrayList<ActivityRecord> activities;
5173
5174 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005175 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005176 dumpFocusedStackOnly);
5177 }
5178
5179 if (activities.size() <= 0) {
5180 return false;
5181 }
5182
5183 String[] newArgs = new String[args.length - opti];
5184 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5185
Louis Changcdec0802019-11-11 11:45:07 +08005186 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005187 boolean needSep = false;
5188 for (int i = activities.size() - 1; i >= 0; i--) {
5189 ActivityRecord r = activities.get(i);
5190 if (needSep) {
5191 pw.println();
5192 }
5193 needSep = true;
5194 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005195 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005196 if (lastTask != task) {
5197 lastTask = task;
5198 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005199 pw.print(" id="); pw.print(lastTask.mTaskId);
5200 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005201 if (dumpAll) {
5202 lastTask.dump(pw, " ");
5203 }
5204 }
5205 }
5206 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5207 }
5208 return true;
5209 }
5210
5211 /**
5212 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5213 * there is a thread associated with the activity.
5214 */
5215 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5216 final ActivityRecord r, String[] args, boolean dumpAll) {
5217 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005218 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005219 synchronized (mGlobalLock) {
5220 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5221 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5222 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005223 if (r.hasProcess()) {
5224 pw.println(r.app.getPid());
5225 appThread = r.app.getThread();
5226 } else {
5227 pw.println("(not running)");
5228 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005229 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005230 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005231 }
5232 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005233 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005234 // flush anything that is already in the PrintWriter since the thread is going
5235 // to write to the file descriptor directly
5236 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005237 try (TransferPipe tp = new TransferPipe()) {
5238 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5239 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005240 } catch (IOException e) {
5241 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5242 } catch (RemoteException e) {
5243 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5244 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005245 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005246 }
5247
sanryhuang498e77e2018-12-06 14:57:01 +08005248 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5249 boolean testPssMode) {
5250 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5251 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5252 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005253 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005254 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5255 st.toString());
5256 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5258 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5259 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005260 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5261 testPssMode);
5262 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005263 }
5264
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005265 int getCurrentUserId() {
5266 return mAmInternal.getCurrentUserId();
5267 }
5268
5269 private void enforceNotIsolatedCaller(String caller) {
5270 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5271 throw new SecurityException("Isolated process not allowed to call " + caller);
5272 }
5273 }
5274
Wale Ogunwalef6733932018-06-27 05:14:34 -07005275 public Configuration getConfiguration() {
5276 Configuration ci;
5277 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005278 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005279 ci.userSetLocale = false;
5280 }
5281 return ci;
5282 }
5283
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005284 /**
5285 * Current global configuration information. Contains general settings for the entire system,
5286 * also corresponds to the merged configuration of the default display.
5287 */
5288 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005289 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005290 // while initializing process record for system, see {@link
5291 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005292 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005293 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 }
5295
5296 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5297 boolean initLocale) {
5298 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5299 }
5300
5301 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5302 boolean initLocale, boolean deferResume) {
5303 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5304 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5305 UserHandle.USER_NULL, deferResume);
5306 }
5307
Wale Ogunwale59507092018-10-29 09:00:30 -07005308 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309 final long origId = Binder.clearCallingIdentity();
5310 try {
5311 synchronized (mGlobalLock) {
5312 updateConfigurationLocked(values, null, false, true, userId,
5313 false /* deferResume */);
5314 }
5315 } finally {
5316 Binder.restoreCallingIdentity(origId);
5317 }
5318 }
5319
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005320 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5321 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5322 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5323 deferResume, null /* result */);
5324 }
5325
5326 /**
5327 * Do either or both things: (1) change the current configuration, and (2)
5328 * make sure the given activity is running with the (now) current
5329 * configuration. Returns true if the activity has been left running, or
5330 * false if <var>starting</var> is being destroyed to match the new
5331 * configuration.
5332 *
5333 * @param userId is only used when persistent parameter is set to true to persist configuration
5334 * for that particular user
5335 */
5336 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5337 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5338 ActivityTaskManagerService.UpdateConfigurationResult result) {
5339 int changes = 0;
5340 boolean kept = true;
5341
Riddle Hsua0022cd2019-09-09 21:12:41 +08005342 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005343 try {
5344 if (values != null) {
5345 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5346 deferResume);
5347 }
5348
5349 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5350 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005351 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005352 }
5353
5354 if (result != null) {
5355 result.changes = changes;
5356 result.activityRelaunched = !kept;
5357 }
5358 return kept;
5359 }
5360
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005361 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005362 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005363 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005364
Louis Chang677921f2019-12-06 16:44:24 +08005365 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005366 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005367
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005368 mTempConfig.setTo(getGlobalConfiguration());
5369 final int changes = mTempConfig.updateFrom(values);
5370 if (changes == 0) {
5371 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5372 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5373 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5374 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005375 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005376 return 0;
5377 }
5378
5379 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5380 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005381 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005382 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5383 values.colorMode,
5384 values.densityDpi,
5385 values.fontScale,
5386 values.hardKeyboardHidden,
5387 values.keyboard,
5388 values.keyboardHidden,
5389 values.mcc,
5390 values.mnc,
5391 values.navigation,
5392 values.navigationHidden,
5393 values.orientation,
5394 values.screenHeightDp,
5395 values.screenLayout,
5396 values.screenWidthDp,
5397 values.smallestScreenWidthDp,
5398 values.touchscreen,
5399 values.uiMode);
5400
5401
5402 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5403 final LocaleList locales = values.getLocales();
5404 int bestLocaleIndex = 0;
5405 if (locales.size() > 1) {
5406 if (mSupportedSystemLocales == null) {
5407 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5408 }
5409 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5410 }
5411 SystemProperties.set("persist.sys.locale",
5412 locales.get(bestLocaleIndex).toLanguageTag());
5413 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005414
5415 final Message m = PooledLambda.obtainMessage(
5416 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5417 locales.get(bestLocaleIndex));
5418 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005419 }
5420
Yunfan Chen75157d72018-07-27 14:47:21 +09005421 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005422
5423 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005424 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005425
5426 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5427 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005428 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005429
5430 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005432
5433 AttributeCache ac = AttributeCache.instance();
5434 if (ac != null) {
5435 ac.updateConfiguration(mTempConfig);
5436 }
5437
5438 // Make sure all resources in our process are updated right now, so that anyone who is going
5439 // to retrieve resource values after we return will be sure to get the new ones. This is
5440 // especially important during boot, where the first config change needs to guarantee all
5441 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005442 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005443
5444 // We need another copy of global config because we're scheduling some calls instead of
5445 // running them in place. We need to be sure that object we send will be handled unchanged.
5446 final Configuration configCopy = new Configuration(mTempConfig);
5447 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005448 final Message msg = PooledLambda.obtainMessage(
5449 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5450 this, userId, configCopy);
5451 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005452 }
5453
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005454 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5455 for (int i = pidMap.size() - 1; i >= 0; i--) {
5456 final int pid = pidMap.keyAt(i);
5457 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005458 if (DEBUG_CONFIGURATION) {
5459 Slog.v(TAG_CONFIGURATION, "Update process config of "
5460 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005461 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005462 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005463 }
5464
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005465 final Message msg = PooledLambda.obtainMessage(
5466 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5467 mAmInternal, changes, initLocale);
5468 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005469
5470 // Override configuration of the default display duplicates global config, so we need to
5471 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005472 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005473 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005474
5475 return changes;
5476 }
5477
Riddle Hsua0022cd2019-09-09 21:12:41 +08005478 /** @see WindowSurfacePlacer#deferLayout */
5479 void deferWindowLayout() {
5480 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5481 // Reset the reasons at the first entrance because we only care about the changes in the
5482 // deferred scope.
5483 mLayoutReasons = 0;
5484 }
5485
5486 mWindowManager.mWindowPlacerLocked.deferLayout();
5487 }
5488
5489 /** @see WindowSurfacePlacer#continueLayout */
5490 void continueWindowLayout() {
5491 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5492 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5493 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5494 }
5495 }
5496
5497 /**
5498 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5499 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5500 * defer count is gone.
5501 */
5502 void addWindowLayoutReasons(@LayoutReason int reasons) {
5503 mLayoutReasons |= reasons;
5504 }
5505
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 private void updateEventDispatchingLocked(boolean booted) {
5507 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5508 }
5509
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005510 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5511 final ContentResolver resolver = mContext.getContentResolver();
5512 Settings.System.putConfigurationForUser(resolver, config, userId);
5513 }
5514
5515 private void sendLocaleToMountDaemonMsg(Locale l) {
5516 try {
5517 IBinder service = ServiceManager.getService("mount");
5518 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5519 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5520 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5521 } catch (RemoteException e) {
5522 Log.e(TAG, "Error storing locale for decryption UI", e);
5523 }
5524 }
5525
Alison Cichowlas3e340502018-08-07 17:15:01 -04005526 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5527 mStartActivitySources.remove(permissionToken);
5528 mExpiredStartAsCallerTokens.add(permissionToken);
5529 }
5530
5531 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5532 mExpiredStartAsCallerTokens.remove(permissionToken);
5533 }
5534
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005535 boolean isActivityStartsLoggingEnabled() {
5536 return mAmInternal.isActivityStartsLoggingEnabled();
5537 }
5538
Michal Karpinski8596ded2018-11-14 14:43:48 +00005539 boolean isBackgroundActivityStartsEnabled() {
5540 return mAmInternal.isBackgroundActivityStartsEnabled();
5541 }
5542
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005544 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 mWindowManager.enableScreenAfterBoot();
5546
5547 synchronized (mGlobalLock) {
5548 updateEventDispatchingLocked(booted);
5549 }
5550 }
5551
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005552 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5553 if (r == null || !r.hasProcess()) {
5554 return KEY_DISPATCHING_TIMEOUT_MS;
5555 }
5556 return getInputDispatchingTimeoutLocked(r.app);
5557 }
5558
5559 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005560 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005561 }
5562
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 /**
5564 * Decide based on the configuration whether we should show the ANR,
5565 * crash, etc dialogs. The idea is that if there is no affordance to
5566 * press the on-screen buttons, or the user experience would be more
5567 * greatly impacted than the crash itself, we shouldn't show the dialog.
5568 *
5569 * A thought: SystemUI might also want to get told about this, the Power
5570 * dialog / global actions also might want different behaviors.
5571 */
5572 private void updateShouldShowDialogsLocked(Configuration config) {
5573 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5574 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5575 && config.navigation == Configuration.NAVIGATION_NONAV);
5576 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5577 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5578 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5579 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5580 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5581 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5582 HIDE_ERROR_DIALOGS, 0) != 0;
5583 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5584 }
5585
5586 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5587 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5588 FONT_SCALE, 1.0f, userId);
5589
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005590 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 if (getGlobalConfiguration().fontScale == scaleFactor) {
5592 return;
5593 }
5594
5595 final Configuration configuration
5596 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5597 configuration.fontScale = scaleFactor;
5598 updatePersistentConfiguration(configuration, userId);
5599 }
5600 }
5601
5602 // Actually is sleeping or shutting down or whatever else in the future
5603 // is an inactive state.
5604 boolean isSleepingOrShuttingDownLocked() {
5605 return isSleepingLocked() || mShuttingDown;
5606 }
5607
5608 boolean isSleepingLocked() {
5609 return mSleeping;
5610 }
5611
Riddle Hsu16567132018-08-16 21:37:47 +08005612 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005613 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005614 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005615 if (task.isActivityTypeStandard()) {
5616 if (mCurAppTimeTracker != r.appTimeTracker) {
5617 // We are switching app tracking. Complete the current one.
5618 if (mCurAppTimeTracker != null) {
5619 mCurAppTimeTracker.stop();
5620 mH.obtainMessage(
5621 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005622 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005623 mCurAppTimeTracker = null;
5624 }
5625 if (r.appTimeTracker != null) {
5626 mCurAppTimeTracker = r.appTimeTracker;
5627 startTimeTrackingFocusedActivityLocked();
5628 }
5629 } else {
5630 startTimeTrackingFocusedActivityLocked();
5631 }
5632 } else {
5633 r.appTimeTracker = null;
5634 }
5635 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5636 // TODO: Probably not, because we don't want to resume voice on switching
5637 // back to this activity
5638 if (task.voiceInteractor != null) {
5639 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5640 } else {
5641 finishRunningVoiceLocked();
5642
5643 if (mLastResumedActivity != null) {
5644 final IVoiceInteractionSession session;
5645
Louis Changcdec0802019-11-11 11:45:07 +08005646 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005647 if (lastResumedActivityTask != null
5648 && lastResumedActivityTask.voiceSession != null) {
5649 session = lastResumedActivityTask.voiceSession;
5650 } else {
5651 session = mLastResumedActivity.voiceSession;
5652 }
5653
5654 if (session != null) {
5655 // We had been in a voice interaction session, but now focused has
5656 // move to something different. Just finish the session, we can't
5657 // return to it and retain the proper state and synchronization with
5658 // the voice interaction service.
5659 finishVoiceTask(session);
5660 }
5661 }
5662 }
5663
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005664 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5665 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005666 }
5667 updateResumedAppTrace(r);
5668 mLastResumedActivity = r;
5669
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005670 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005671
5672 applyUpdateLockStateLocked(r);
5673 applyUpdateVrModeLocked(r);
5674
Jeff Changd136e772019-11-05 20:33:52 +08005675 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005676 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005677 r == null ? "NULL" : r.shortComponentName,
5678 reason);
5679 }
5680
5681 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5682 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005683 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005684 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005685 updateSleepIfNeededLocked();
5686 return token;
5687 }
5688 }
5689
5690 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005691 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005692 final boolean wasSleeping = mSleeping;
5693 boolean updateOomAdj = false;
5694
5695 if (!shouldSleep) {
5696 // If wasSleeping is true, we need to wake up activity manager state from when
5697 // we started sleeping. In either case, we need to apply the sleep tokens, which
5698 // will wake up stacks or put them to sleep as appropriate.
5699 if (wasSleeping) {
5700 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005701 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5702 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005703 startTimeTrackingFocusedActivityLocked();
5704 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005705 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005706 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5707 }
Louis Chang149d5c82019-12-30 09:47:39 +08005708 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005709 if (wasSleeping) {
5710 updateOomAdj = true;
5711 }
5712 } else if (!mSleeping && shouldSleep) {
5713 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005714 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5715 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005716 if (mCurAppTimeTracker != null) {
5717 mCurAppTimeTracker.stop();
5718 }
5719 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005720 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005721 mStackSupervisor.goingToSleepLocked();
5722 updateResumedAppTrace(null /* resumed */);
5723 updateOomAdj = true;
5724 }
5725 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005726 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005727 }
5728 }
5729
5730 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005731 mH.removeCallbacks(mUpdateOomAdjRunnable);
5732 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005733 }
5734
Wale Ogunwale53783742018-09-16 10:21:51 -07005735 void updateCpuStats() {
5736 mH.post(mAmInternal::updateCpuStats);
5737 }
5738
Hui Yu03d12402018-12-06 18:00:37 -08005739 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5740 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005741 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5742 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005743 mH.sendMessage(m);
5744 }
5745
Hui Yu03d12402018-12-06 18:00:37 -08005746 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005747 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005748 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005749 if (task != null) {
5750 final ActivityRecord rootActivity = task.getRootActivity();
5751 if (rootActivity != null) {
5752 taskRoot = rootActivity.mActivityComponent;
5753 }
5754 }
5755
Hui Yu03d12402018-12-06 18:00:37 -08005756 final Message m = PooledLambda.obtainMessage(
5757 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005758 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005759 mH.sendMessage(m);
5760 }
5761
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005762 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5763 String hostingType) {
5764 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005765 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5766 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005767 + activity.processName);
5768 }
5769 // Post message to start process to avoid possible deadlock of calling into AMS with the
5770 // ATMS lock held.
5771 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5772 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5773 isTop, hostingType, activity.intent.getComponent());
5774 mH.sendMessage(m);
5775 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005776 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005777 }
5778 }
5779
Wale Ogunwale53783742018-09-16 10:21:51 -07005780 void setBooting(boolean booting) {
5781 mAmInternal.setBooting(booting);
5782 }
5783
5784 boolean isBooting() {
5785 return mAmInternal.isBooting();
5786 }
5787
5788 void setBooted(boolean booted) {
5789 mAmInternal.setBooted(booted);
5790 }
5791
5792 boolean isBooted() {
5793 return mAmInternal.isBooted();
5794 }
5795
5796 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5797 mH.post(() -> {
5798 if (finishBooting) {
5799 mAmInternal.finishBooting();
5800 }
5801 if (enableScreen) {
5802 mInternal.enableScreenAfterBoot(isBooted());
5803 }
5804 });
5805 }
5806
5807 void setHeavyWeightProcess(ActivityRecord root) {
5808 mHeavyWeightProcess = root.app;
5809 final Message m = PooledLambda.obtainMessage(
5810 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005811 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005812 mH.sendMessage(m);
5813 }
5814
5815 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5816 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5817 return;
5818 }
5819
5820 mHeavyWeightProcess = null;
5821 final Message m = PooledLambda.obtainMessage(
5822 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5823 proc.mUserId);
5824 mH.sendMessage(m);
5825 }
5826
5827 private void cancelHeavyWeightProcessNotification(int userId) {
5828 final INotificationManager inm = NotificationManager.getService();
5829 if (inm == null) {
5830 return;
5831 }
5832 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005833 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005834 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5835 } catch (RuntimeException e) {
5836 Slog.w(TAG, "Error canceling notification for service", e);
5837 } catch (RemoteException e) {
5838 }
5839
5840 }
5841
5842 private void postHeavyWeightProcessNotification(
5843 WindowProcessController proc, Intent intent, int userId) {
5844 if (proc == null) {
5845 return;
5846 }
5847
5848 final INotificationManager inm = NotificationManager.getService();
5849 if (inm == null) {
5850 return;
5851 }
5852
5853 try {
5854 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5855 String text = mContext.getString(R.string.heavy_weight_notification,
5856 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5857 Notification notification =
5858 new Notification.Builder(context,
5859 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5860 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5861 .setWhen(0)
5862 .setOngoing(true)
5863 .setTicker(text)
5864 .setColor(mContext.getColor(
5865 com.android.internal.R.color.system_notification_accent_color))
5866 .setContentTitle(text)
5867 .setContentText(
5868 mContext.getText(R.string.heavy_weight_notification_detail))
5869 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5870 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5871 new UserHandle(userId)))
5872 .build();
5873 try {
5874 inm.enqueueNotificationWithTag("android", "android", null,
5875 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5876 } catch (RuntimeException e) {
5877 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5878 } catch (RemoteException e) {
5879 }
5880 } catch (PackageManager.NameNotFoundException e) {
5881 Slog.w(TAG, "Unable to create context for heavy notification", e);
5882 }
5883
5884 }
5885
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005886 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5887 IBinder token, String resultWho, int requestCode, Intent[] intents,
5888 String[] resolvedTypes, int flags, Bundle bOptions) {
5889
5890 ActivityRecord activity = null;
5891 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5892 activity = ActivityRecord.isInStackLocked(token);
5893 if (activity == null) {
5894 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5895 return null;
5896 }
5897 if (activity.finishing) {
5898 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5899 return null;
5900 }
5901 }
5902
5903 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5904 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5905 bOptions);
5906 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5907 if (noCreate) {
5908 return rec;
5909 }
5910 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5911 if (activity.pendingResults == null) {
5912 activity.pendingResults = new HashSet<>();
5913 }
5914 activity.pendingResults.add(rec.ref);
5915 }
5916 return rec;
5917 }
5918
Andrii Kulian52d255c2018-07-13 11:32:19 -07005919 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005920 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005921 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005922 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5923 mCurAppTimeTracker.start(resumedActivity.packageName);
5924 }
5925 }
5926
5927 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5928 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005929 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005930 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5931 }
5932 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005933 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005934 constructResumedTraceName(resumed.packageName), 0);
5935 }
5936 mTracedResumedActivity = resumed;
5937 }
5938
5939 private String constructResumedTraceName(String packageName) {
5940 return "focused app: " + packageName;
5941 }
5942
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005943 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005944 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005945 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005946 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005947 // mainStack is null during startup.
5948 if (mainStack != null) {
5949 if (changes != 0 && starting == null) {
5950 // If the configuration changed, and the caller is not already
5951 // in the process of starting an activity, then find the top
5952 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005953 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005954 }
5955
5956 if (starting != null) {
5957 kept = starting.ensureActivityConfiguration(changes,
5958 false /* preserveWindow */);
5959 // And we need to make sure at this point that all other activities
5960 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005961 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005962 !PRESERVE_WINDOWS);
5963 }
5964 }
5965
5966 return kept;
5967 }
5968
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005969 void scheduleAppGcsLocked() {
5970 mH.post(() -> mAmInternal.scheduleAppGcs());
5971 }
5972
Wale Ogunwale53783742018-09-16 10:21:51 -07005973 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5974 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5975 }
5976
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005977 /**
5978 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5979 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5980 * on demand.
5981 */
5982 IPackageManager getPackageManager() {
5983 return AppGlobals.getPackageManager();
5984 }
5985
5986 PackageManagerInternal getPackageManagerInternalLocked() {
5987 if (mPmInternal == null) {
5988 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5989 }
5990 return mPmInternal;
5991 }
5992
Hai Zhangf4da9be2019-05-01 13:46:06 +08005993 PermissionPolicyInternal getPermissionPolicyInternal() {
5994 if (mPermissionPolicyInternal == null) {
5995 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5996 }
5997 return mPermissionPolicyInternal;
5998 }
5999
Wale Ogunwale008163e2018-07-23 23:11:08 -07006000 AppWarnings getAppWarningsLocked() {
6001 return mAppWarnings;
6002 }
6003
Wale Ogunwale214f3482018-10-04 11:00:47 -07006004 Intent getHomeIntent() {
6005 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
6006 intent.setComponent(mTopComponent);
6007 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6008 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6009 intent.addCategory(Intent.CATEGORY_HOME);
6010 }
6011 return intent;
6012 }
6013
Chilun2ef71f72018-11-16 17:57:15 +08006014 /**
6015 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
6016 * activities.
6017 *
6018 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
6019 * component defined in config_secondaryHomeComponent.
6020 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
6021 */
6022 Intent getSecondaryHomeIntent(String preferredPackage) {
6023 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07006024 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
6025 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
6026 if (preferredPackage == null || useSystemProvidedLauncher) {
6027 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08006028 final String secondaryHomeComponent = mContext.getResources().getString(
6029 com.android.internal.R.string.config_secondaryHomeComponent);
6030 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
6031 } else {
6032 intent.setPackage(preferredPackage);
6033 }
6034 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6035 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6036 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
6037 }
6038 return intent;
6039 }
6040
Wale Ogunwale214f3482018-10-04 11:00:47 -07006041 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
6042 if (info == null) return null;
6043 ApplicationInfo newInfo = new ApplicationInfo(info);
6044 newInfo.initForUser(userId);
6045 return newInfo;
6046 }
6047
Wale Ogunwale9c103022018-10-18 07:44:54 -07006048 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006049 if (uid == SYSTEM_UID) {
6050 // The system gets to run in any process. If there are multiple processes with the same
6051 // uid, just pick the first (this should never happen).
6052 final SparseArray<WindowProcessController> procs =
6053 mProcessNames.getMap().get(processName);
6054 if (procs == null) return null;
6055 final int procCount = procs.size();
6056 for (int i = 0; i < procCount; i++) {
6057 final int procUid = procs.keyAt(i);
6058 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
6059 // Don't use an app process or different user process for system component.
6060 continue;
6061 }
6062 return procs.valueAt(i);
6063 }
6064 }
6065
6066 return mProcessNames.get(processName, uid);
6067 }
6068
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006069 WindowProcessController getProcessController(IApplicationThread thread) {
6070 if (thread == null) {
6071 return null;
6072 }
6073
6074 final IBinder threadBinder = thread.asBinder();
6075 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6076 for (int i = pmap.size()-1; i >= 0; i--) {
6077 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6078 for (int j = procs.size() - 1; j >= 0; j--) {
6079 final WindowProcessController proc = procs.valueAt(j);
6080 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6081 return proc;
6082 }
6083 }
6084 }
6085
6086 return null;
6087 }
6088
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006089 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006090 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006091 if (proc == null) return null;
6092 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6093 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006094 }
6095 return null;
6096 }
6097
Riddle Hsua0536432019-02-16 00:38:59 +08006098 int getUidState(int uid) {
6099 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006100 }
6101
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006102 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006103 // A uid is considered to be foreground if it has a visible non-toast window.
6104 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006105 }
6106
Ricky Wai96f5c352019-04-10 18:40:17 +01006107 boolean isDeviceOwner(int uid) {
6108 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006109 }
6110
Ricky Wai96f5c352019-04-10 18:40:17 +01006111 void setDeviceOwnerUid(int uid) {
6112 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006113 }
6114
Wale Ogunwale9de19442018-10-18 19:05:03 -07006115 /**
6116 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6117 * the whitelist
6118 */
6119 String getPendingTempWhitelistTagForUidLocked(int uid) {
6120 return mPendingTempWhitelist.get(uid);
6121 }
6122
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006123 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6124 if (true || Build.IS_USER) {
6125 return;
6126 }
6127
6128 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6129 StrictMode.allowThreadDiskWrites();
6130 try {
6131 File tracesDir = new File("/data/anr");
6132 File tracesFile = null;
6133 try {
6134 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6135
6136 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006137 String timeString =
6138 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6139 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006140 sb.append(": ");
6141 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6142 sb.append(" since ");
6143 sb.append(msg);
6144 FileOutputStream fos = new FileOutputStream(tracesFile);
6145 fos.write(sb.toString().getBytes());
6146 if (app == null) {
6147 fos.write("\n*** No application process!".getBytes());
6148 }
6149 fos.close();
6150 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6151 } catch (IOException e) {
6152 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6153 return;
6154 }
6155
6156 if (app != null && app.getPid() > 0) {
6157 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6158 firstPids.add(app.getPid());
6159 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6160 }
6161
6162 File lastTracesFile = null;
6163 File curTracesFile = null;
6164 for (int i=9; i>=0; i--) {
6165 String name = String.format(Locale.US, "slow%02d.txt", i);
6166 curTracesFile = new File(tracesDir, name);
6167 if (curTracesFile.exists()) {
6168 if (lastTracesFile != null) {
6169 curTracesFile.renameTo(lastTracesFile);
6170 } else {
6171 curTracesFile.delete();
6172 }
6173 }
6174 lastTracesFile = curTracesFile;
6175 }
6176 tracesFile.renameTo(curTracesFile);
6177 } finally {
6178 StrictMode.setThreadPolicy(oldPolicy);
6179 }
6180 }
6181
Michal Karpinskida34cd42019-04-02 19:46:52 +01006182 boolean isAssociatedCompanionApp(int userId, int uid) {
6183 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6184 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006185 return false;
6186 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006187 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006188 }
6189
Issei Suzuki734bc942019-06-05 13:59:52 +02006190 void notifySingleTaskDisplayEmpty(int displayId) {
6191 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6192 }
6193
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006194 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006195 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006196
6197
Wale Ogunwale98875612018-10-12 07:53:02 -07006198 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6199 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006200
Riddle Hsud93a6c42018-11-29 21:50:06 +08006201 H(Looper looper) {
6202 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006203 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006204
6205 @Override
6206 public void handleMessage(Message msg) {
6207 switch (msg.what) {
6208 case REPORT_TIME_TRACKER_MSG: {
6209 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6210 tracker.deliverResult(mContext);
6211 } break;
6212 }
6213 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006214 }
6215
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006216 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006217 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006218
6219 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006220 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006221 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006222
6223 @Override
6224 public void handleMessage(Message msg) {
6225 switch (msg.what) {
6226 case DISMISS_DIALOG_UI_MSG: {
6227 final Dialog d = (Dialog) msg.obj;
6228 d.dismiss();
6229 break;
6230 }
6231 }
6232 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006233 }
6234
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235 final class LocalService extends ActivityTaskManagerInternal {
6236 @Override
6237 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006238 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006239 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006240 }
6241
6242 @Override
6243 public ComponentName getHomeActivityForUser(int userId) {
6244 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006245 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006246 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006247 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006248 }
6249 }
6250
6251 @Override
6252 public void onLocalVoiceInteractionStarted(IBinder activity,
6253 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6254 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006255 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 }
6257 }
6258
6259 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006260 public void notifySingleTaskDisplayDrawn(int displayId) {
6261 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6262 }
6263
6264 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006265 public void notifyAppTransitionFinished() {
6266 synchronized (mGlobalLock) {
6267 mStackSupervisor.notifyAppTransitionDone();
6268 }
6269 }
6270
6271 @Override
6272 public void notifyAppTransitionCancelled() {
6273 synchronized (mGlobalLock) {
6274 mStackSupervisor.notifyAppTransitionDone();
6275 }
6276 }
6277
6278 @Override
6279 public List<IBinder> getTopVisibleActivities() {
6280 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006281 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 }
6283 }
6284
6285 @Override
6286 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6287 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006288 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290 }
6291
6292 @Override
6293 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6294 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006295 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006296 final String[] resolvedTypes = new String[intents.length];
6297
6298 // UID of the package on user userId.
6299 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6300 // packageUid may not be initialized.
6301 int packageUid = 0;
6302 final long ident = Binder.clearCallingIdentity();
6303
6304 try {
6305 for (int i = 0; i < intents.length; i++) {
6306 resolvedTypes[i] =
6307 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6308 }
6309
6310 packageUid = AppGlobals.getPackageManager().getPackageUid(
6311 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6312 } catch (RemoteException e) {
6313 // Shouldn't happen.
6314 } finally {
6315 Binder.restoreCallingIdentity(ident);
6316 }
6317
Riddle Hsu591bf612019-02-14 17:55:31 +08006318 return getActivityStartController().startActivitiesInPackage(
6319 packageUid, packageName,
6320 intents, resolvedTypes, null /* resultTo */,
6321 SafeActivityOptions.fromBundle(bOptions), userId,
6322 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6323 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006324 }
6325
6326 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006327 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6328 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6329 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6330 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006331 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006332 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006333 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6334 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6335 userId, validateIncomingUser, originatingPendingIntent,
6336 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006337 }
6338 }
6339
6340 @Override
6341 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6342 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6343 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006344 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006345 PendingIntentRecord originatingPendingIntent,
6346 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006347 synchronized (mGlobalLock) {
6348 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6349 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6350 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006351 validateIncomingUser, originatingPendingIntent,
6352 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006353 }
6354 }
6355
6356 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006357 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6358 Intent intent, Bundle options, int userId) {
6359 return ActivityTaskManagerService.this.startActivityAsUser(
6360 caller, callerPacakge, intent,
6361 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6362 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6363 false /*validateIncomingUser*/);
6364 }
6365
6366 @Override
lumark588a3e82018-07-20 18:53:54 +08006367 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006368 synchronized (mGlobalLock) {
6369
6370 // We might change the visibilities here, so prepare an empty app transition which
6371 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006372 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006373 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006374 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006375 return;
6376 }
Louis Chang677921f2019-12-06 16:44:24 +08006377 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006378 final boolean wasTransitionSet =
6379 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006380 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006381 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006382 }
Louis Chang149d5c82019-12-30 09:47:39 +08006383 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006384
6385 // If there was a transition set already we don't want to interfere with it as we
6386 // might be starting it too early.
6387 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006388 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006389 }
6390 }
6391 if (callback != null) {
6392 callback.run();
6393 }
6394 }
6395
6396 @Override
6397 public void notifyKeyguardTrustedChanged() {
6398 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006399 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006400 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006401 }
6402 }
6403 }
6404
6405 /**
6406 * Called after virtual display Id is updated by
6407 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6408 * {@param vrVr2dDisplayId}.
6409 */
6410 @Override
6411 public void setVr2dDisplayId(int vr2dDisplayId) {
6412 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6413 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006414 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006415 }
6416 }
6417
6418 @Override
6419 public void setFocusedActivity(IBinder token) {
6420 synchronized (mGlobalLock) {
6421 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6422 if (r == null) {
6423 throw new IllegalArgumentException(
6424 "setFocusedActivity: No activity record matching token=" + token);
6425 }
Louis Chang19443452018-10-09 12:10:21 +08006426 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006427 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006428 }
6429 }
6430 }
6431
6432 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006433 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006434 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006435 }
6436
6437 @Override
6438 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006439 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006440 }
6441
6442 @Override
6443 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006444 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006445 }
6446
6447 @Override
6448 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6449 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6450 }
6451
6452 @Override
6453 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006454 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006455 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006456
6457 @Override
6458 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6459 synchronized (mGlobalLock) {
6460 mActiveVoiceInteractionServiceComponent = component;
6461 }
6462 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006463
6464 @Override
6465 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6466 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6467 return;
6468 }
6469 synchronized (mGlobalLock) {
6470 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6471 if (types == null) {
6472 if (uid < 0) {
6473 return;
6474 }
6475 types = new ArrayMap<>();
6476 mAllowAppSwitchUids.put(userId, types);
6477 }
6478 if (uid < 0) {
6479 types.remove(type);
6480 } else {
6481 types.put(type, uid);
6482 }
6483 }
6484 }
6485
6486 @Override
6487 public void onUserStopped(int userId) {
6488 synchronized (mGlobalLock) {
6489 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6490 mAllowAppSwitchUids.remove(userId);
6491 }
6492 }
6493
6494 @Override
6495 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6496 synchronized (mGlobalLock) {
6497 return ActivityTaskManagerService.this.isGetTasksAllowed(
6498 caller, callingPid, callingUid);
6499 }
6500 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006501
Riddle Hsua0536432019-02-16 00:38:59 +08006502 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006503 @Override
6504 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006505 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006506 mProcessNames.put(proc.mName, proc.mUid, proc);
6507 }
6508 }
6509
Riddle Hsua0536432019-02-16 00:38:59 +08006510 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006511 @Override
6512 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006513 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006514 mProcessNames.remove(name, uid);
6515 }
6516 }
6517
Riddle Hsua0536432019-02-16 00:38:59 +08006518 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006519 @Override
6520 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006521 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006522 if (proc == mHomeProcess) {
6523 mHomeProcess = null;
6524 }
6525 if (proc == mPreviousProcess) {
6526 mPreviousProcess = null;
6527 }
6528 }
6529 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006530
Riddle Hsua0536432019-02-16 00:38:59 +08006531 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006532 @Override
6533 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006534 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006535 return mTopProcessState;
6536 }
6537 }
6538
Riddle Hsua0536432019-02-16 00:38:59 +08006539 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006540 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006541 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006542 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006543 return proc == mHeavyWeightProcess;
6544 }
6545 }
6546
Riddle Hsua0536432019-02-16 00:38:59 +08006547 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006548 @Override
6549 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006550 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006551 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6552 }
6553 }
6554
6555 @Override
6556 public void finishHeavyWeightApp() {
6557 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006558 if (mHeavyWeightProcess != null) {
6559 mHeavyWeightProcess.finishActivities();
6560 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006561 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6562 mHeavyWeightProcess);
6563 }
6564 }
6565
Riddle Hsua0536432019-02-16 00:38:59 +08006566 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006567 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006568 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006569 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006570 return isSleepingLocked();
6571 }
6572 }
6573
6574 @Override
6575 public boolean isShuttingDown() {
6576 synchronized (mGlobalLock) {
6577 return mShuttingDown;
6578 }
6579 }
6580
6581 @Override
6582 public boolean shuttingDown(boolean booted, int timeout) {
6583 synchronized (mGlobalLock) {
6584 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006585 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006586 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006587 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006588 return mStackSupervisor.shutdownLocked(timeout);
6589 }
6590 }
6591
6592 @Override
6593 public void enableScreenAfterBoot(boolean booted) {
6594 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006595 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006596 mWindowManager.enableScreenAfterBoot();
6597 updateEventDispatchingLocked(booted);
6598 }
6599 }
6600
6601 @Override
6602 public boolean showStrictModeViolationDialog() {
6603 synchronized (mGlobalLock) {
6604 return mShowDialogs && !mSleeping && !mShuttingDown;
6605 }
6606 }
6607
6608 @Override
6609 public void showSystemReadyErrorDialogsIfNeeded() {
6610 synchronized (mGlobalLock) {
6611 try {
6612 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6613 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6614 + " data partition or your device will be unstable.");
6615 mUiHandler.post(() -> {
6616 if (mShowDialogs) {
6617 AlertDialog d = new BaseErrorDialog(mUiContext);
6618 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6619 d.setCancelable(false);
6620 d.setTitle(mUiContext.getText(R.string.android_system_label));
6621 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6622 d.setButton(DialogInterface.BUTTON_POSITIVE,
6623 mUiContext.getText(R.string.ok),
6624 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6625 d.show();
6626 }
6627 });
6628 }
6629 } catch (RemoteException e) {
6630 }
6631
6632 if (!Build.isBuildConsistent()) {
6633 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6634 mUiHandler.post(() -> {
6635 if (mShowDialogs) {
6636 AlertDialog d = new BaseErrorDialog(mUiContext);
6637 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6638 d.setCancelable(false);
6639 d.setTitle(mUiContext.getText(R.string.android_system_label));
6640 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6641 d.setButton(DialogInterface.BUTTON_POSITIVE,
6642 mUiContext.getText(R.string.ok),
6643 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6644 d.show();
6645 }
6646 });
6647 }
6648 }
6649 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006650
6651 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006652 public void onProcessMapped(int pid, WindowProcessController proc) {
6653 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006654 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006655 }
6656 }
6657
6658 @Override
6659 public void onProcessUnMapped(int pid) {
6660 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006661 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006662 }
6663 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006664
6665 @Override
6666 public void onPackageDataCleared(String name) {
6667 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006668 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006669 mAppWarnings.onPackageDataCleared(name);
6670 }
6671 }
6672
6673 @Override
6674 public void onPackageUninstalled(String name) {
6675 synchronized (mGlobalLock) {
6676 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006677 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006678 }
6679 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006680
6681 @Override
6682 public void onPackageAdded(String name, boolean replacing) {
6683 synchronized (mGlobalLock) {
6684 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6685 }
6686 }
6687
6688 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006689 public void onPackageReplaced(ApplicationInfo aInfo) {
6690 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006691 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692 }
6693 }
6694
6695 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006696 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6697 synchronized (mGlobalLock) {
6698 return compatibilityInfoForPackageLocked(ai);
6699 }
6700 }
6701
Yunfan Chen75157d72018-07-27 14:47:21 +09006702 /**
6703 * Set the corresponding display information for the process global configuration. To be
6704 * called when we need to show IME on a different display.
6705 *
6706 * @param pid The process id associated with the IME window.
6707 * @param displayId The ID of the display showing the IME.
6708 */
6709 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006710 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006711 // Don't update process-level configuration for Multi-Client IME process since other
6712 // IMEs on other displays will also receive this configuration change due to IME
6713 // services use the same application config/context.
6714 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006715
Yunfan Chen75157d72018-07-27 14:47:21 +09006716 if (pid == MY_PID || pid < 0) {
6717 if (DEBUG_CONFIGURATION) {
6718 Slog.w(TAG,
6719 "Trying to update display configuration for system/invalid process.");
6720 }
6721 return;
6722 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006723 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006724 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006725 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006726 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006727 // Call might come when display is not yet added or has been removed.
6728 if (DEBUG_CONFIGURATION) {
6729 Slog.w(TAG, "Trying to update display configuration for non-existing "
6730 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006731 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006732 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006733 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006734 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006735 if (process == null) {
6736 if (DEBUG_CONFIGURATION) {
6737 Slog.w(TAG, "Trying to update display configuration for invalid "
6738 + "process, pid=" + pid);
6739 }
6740 return;
6741 }
lumarkddc77fb2019-06-27 22:22:23 +08006742 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006743 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006744 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006745 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006746
6747 @Override
6748 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006749 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006750 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006751 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006752 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006753 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006754 }
6755 }
6756 }
6757
6758 @Override
6759 public void clearPendingResultForActivity(IBinder activityToken,
6760 WeakReference<PendingIntentRecord> pir) {
6761 synchronized (mGlobalLock) {
6762 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6763 if (r != null && r.pendingResults != null) {
6764 r.pendingResults.remove(pir);
6765 }
6766 }
6767 }
6768
6769 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006770 public ActivityTokens getTopActivityForTask(int taskId) {
6771 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006772 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006773 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006774 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6775 + " Requested task not found");
6776 return null;
6777 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006778 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006779 if (activity == null) {
6780 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6781 + " Requested activity not found");
6782 return null;
6783 }
6784 if (!activity.attachedToProcess()) {
6785 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6786 + activity);
6787 return null;
6788 }
6789 return new ActivityTokens(activity.appToken, activity.assistToken,
6790 activity.app.getThread());
6791 }
6792 }
6793
6794 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006795 public IIntentSender getIntentSender(int type, String packageName,
6796 int callingUid, int userId, IBinder token, String resultWho,
6797 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6798 Bundle bOptions) {
6799 synchronized (mGlobalLock) {
6800 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6801 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6802 }
6803 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006804
6805 @Override
6806 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6807 synchronized (mGlobalLock) {
6808 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6809 if (r == null) {
6810 return null;
6811 }
6812 if (r.mServiceConnectionsHolder == null) {
6813 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6814 ActivityTaskManagerService.this, r);
6815 }
6816
6817 return r.mServiceConnectionsHolder;
6818 }
6819 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006820
6821 @Override
6822 public Intent getHomeIntent() {
6823 synchronized (mGlobalLock) {
6824 return ActivityTaskManagerService.this.getHomeIntent();
6825 }
6826 }
6827
6828 @Override
6829 public boolean startHomeActivity(int userId, String reason) {
6830 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006831 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006832 }
6833 }
6834
6835 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006836 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006837 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006838 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006839 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006840 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006841 }
Chilun8b1f1be2019-03-13 17:14:36 +08006842 }
6843
6844 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006845 public boolean startHomeOnAllDisplays(int userId, String reason) {
6846 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006847 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006848 }
6849 }
6850
Riddle Hsua0536432019-02-16 00:38:59 +08006851 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006852 @Override
6853 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006854 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006855 if (mFactoryTest == FACTORY_TEST_OFF) {
6856 return false;
6857 }
6858 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6859 && wpc.mName.equals(mTopComponent.getPackageName())) {
6860 return true;
6861 }
6862 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6863 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6864 }
6865 }
6866
6867 @Override
6868 public void updateTopComponentForFactoryTest() {
6869 synchronized (mGlobalLock) {
6870 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6871 return;
6872 }
6873 final ResolveInfo ri = mContext.getPackageManager()
6874 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6875 final CharSequence errorMsg;
6876 if (ri != null) {
6877 final ActivityInfo ai = ri.activityInfo;
6878 final ApplicationInfo app = ai.applicationInfo;
6879 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6880 mTopAction = Intent.ACTION_FACTORY_TEST;
6881 mTopData = null;
6882 mTopComponent = new ComponentName(app.packageName, ai.name);
6883 errorMsg = null;
6884 } else {
6885 errorMsg = mContext.getResources().getText(
6886 com.android.internal.R.string.factorytest_not_system);
6887 }
6888 } else {
6889 errorMsg = mContext.getResources().getText(
6890 com.android.internal.R.string.factorytest_no_action);
6891 }
6892 if (errorMsg == null) {
6893 return;
6894 }
6895
6896 mTopAction = null;
6897 mTopData = null;
6898 mTopComponent = null;
6899 mUiHandler.post(() -> {
6900 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6901 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006902 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006903 });
6904 }
6905 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006906
Riddle Hsua0536432019-02-16 00:38:59 +08006907 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 @Override
6909 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6910 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006911 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006912 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006913 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006914
6915 wpc.clearRecentTasks();
6916 wpc.clearActivities();
6917
6918 if (wpc.isInstrumenting()) {
6919 finishInstrumentationCallback.run();
6920 }
6921
Jorim Jaggid0752812018-10-16 16:07:20 +02006922 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006923 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006924 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006925 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006926 // If there was nothing to resume, and we are not already restarting
6927 // this process, but there is a visible activity that is hosted by the
6928 // process...then make sure all visible activities are running, taking
6929 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006930 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006931 !PRESERVE_WINDOWS);
6932 }
6933 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006934 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006935 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 }
6937 }
6938 }
6939
6940 @Override
6941 public void closeSystemDialogs(String reason) {
6942 enforceNotIsolatedCaller("closeSystemDialogs");
6943
6944 final int pid = Binder.getCallingPid();
6945 final int uid = Binder.getCallingUid();
6946 final long origId = Binder.clearCallingIdentity();
6947 try {
6948 synchronized (mGlobalLock) {
6949 // Only allow this from foreground processes, so that background
6950 // applications can't abuse it to prevent system UI from being shown.
6951 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006952 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006953 if (!proc.isPerceptible()) {
6954 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6955 + " from background process " + proc);
6956 return;
6957 }
6958 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006959 mWindowManager.closeSystemDialogs(reason);
6960
Louis Chang149d5c82019-12-30 09:47:39 +08006961 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006963 // Call into AM outside the synchronized block.
6964 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006965 } finally {
6966 Binder.restoreCallingIdentity(origId);
6967 }
6968 }
6969
6970 @Override
6971 public void cleanupDisabledPackageComponents(
6972 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6973 synchronized (mGlobalLock) {
6974 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006975 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006976 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006977 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006978 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006979 }
6980
6981 // Clean-up disabled tasks
6982 getRecentTasks().cleanupDisabledPackageTasksLocked(
6983 packageName, disabledClasses, userId);
6984 }
6985 }
6986
6987 @Override
6988 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6989 int userId) {
6990 synchronized (mGlobalLock) {
6991
6992 boolean didSomething =
6993 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006994 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 null, doit, evenPersistent, userId);
6996 return didSomething;
6997 }
6998 }
6999
7000 @Override
7001 public void resumeTopActivities(boolean scheduleIdle) {
7002 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007003 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007004 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08007005 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007006 }
7007 }
7008 }
7009
Riddle Hsua0536432019-02-16 00:38:59 +08007010 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007011 @Override
7012 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08007013 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
7015 }
7016 }
7017
Riddle Hsua0536432019-02-16 00:38:59 +08007018 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007019 @Override
7020 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08007021 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007022 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
7023 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
7024 }
7025 try {
Louis Chang149d5c82019-12-30 09:47:39 +08007026 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007027 } finally {
7028 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
7029 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 }
7031 }
7032
7033 @Override
7034 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
7035 try {
7036 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
7037 throw new SecurityException("Only privileged app can call notifyLockedProfile");
7038 }
7039 } catch (RemoteException ex) {
7040 throw new SecurityException("Fail to check is caller a privileged app", ex);
7041 }
7042
7043 synchronized (mGlobalLock) {
7044 final long ident = Binder.clearCallingIdentity();
7045 try {
7046 if (mAmInternal.shouldConfirmCredentials(userId)) {
7047 if (mKeyguardController.isKeyguardLocked()) {
7048 // Showing launcher to avoid user entering credential twice.
7049 startHomeActivity(currentUserId, "notifyLockedProfile");
7050 }
Louis Chang149d5c82019-12-30 09:47:39 +08007051 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007052 }
7053 } finally {
7054 Binder.restoreCallingIdentity(ident);
7055 }
7056 }
7057 }
7058
7059 @Override
7060 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7061 mAmInternal.enforceCallingPermission(
7062 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7063
7064 synchronized (mGlobalLock) {
7065 final long ident = Binder.clearCallingIdentity();
7066 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007067 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7068 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007069 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007070 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7071 UserHandle.CURRENT);
7072 } finally {
7073 Binder.restoreCallingIdentity(ident);
7074 }
7075 }
7076 }
7077
7078 @Override
7079 public void writeActivitiesToProto(ProtoOutputStream proto) {
7080 synchronized (mGlobalLock) {
7081 // The output proto of "activity --proto activities"
7082 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007083 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007084 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7085 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007086 }
7087 }
7088
7089 @Override
7090 public void saveANRState(String reason) {
7091 synchronized (mGlobalLock) {
7092 final StringWriter sw = new StringWriter();
7093 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7094 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7095 if (reason != null) {
7096 pw.println(" Reason: " + reason);
7097 }
7098 pw.println();
7099 getActivityStartController().dump(pw, " ", null);
7100 pw.println();
7101 pw.println("-------------------------------------------------------------------------------");
7102 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7103 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7104 "" /* header */);
7105 pw.println();
7106 pw.close();
7107
7108 mLastANRState = sw.toString();
7109 }
7110 }
7111
7112 @Override
7113 public void clearSavedANRState() {
7114 synchronized (mGlobalLock) {
7115 mLastANRState = null;
7116 }
7117 }
7118
7119 @Override
7120 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7121 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7122 synchronized (mGlobalLock) {
7123 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7124 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7125 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7126 dumpLastANRLocked(pw);
7127 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7128 dumpLastANRTracesLocked(pw);
7129 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7130 dumpActivityStarterLocked(pw, dumpPackage);
7131 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7132 dumpActivityContainersLocked(pw);
7133 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7134 if (getRecentTasks() != null) {
7135 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7136 }
7137 }
7138 }
7139 }
7140
7141 @Override
7142 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7143 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7144 int wakefulness) {
7145 synchronized (mGlobalLock) {
7146 if (mHomeProcess != null && (dumpPackage == null
7147 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7148 if (needSep) {
7149 pw.println();
7150 needSep = false;
7151 }
7152 pw.println(" mHomeProcess: " + mHomeProcess);
7153 }
7154 if (mPreviousProcess != null && (dumpPackage == null
7155 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7156 if (needSep) {
7157 pw.println();
7158 needSep = false;
7159 }
7160 pw.println(" mPreviousProcess: " + mPreviousProcess);
7161 }
7162 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7163 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7164 StringBuilder sb = new StringBuilder(128);
7165 sb.append(" mPreviousProcessVisibleTime: ");
7166 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7167 pw.println(sb);
7168 }
7169 if (mHeavyWeightProcess != null && (dumpPackage == null
7170 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7171 if (needSep) {
7172 pw.println();
7173 needSep = false;
7174 }
7175 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7176 }
7177 if (dumpPackage == null) {
7178 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007179 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181 if (dumpAll) {
7182 if (dumpPackage == null) {
7183 pw.println(" mConfigWillChange: "
7184 + getTopDisplayFocusedStack().mConfigWillChange);
7185 }
7186 if (mCompatModePackages.getPackages().size() > 0) {
7187 boolean printed = false;
7188 for (Map.Entry<String, Integer> entry
7189 : mCompatModePackages.getPackages().entrySet()) {
7190 String pkg = entry.getKey();
7191 int mode = entry.getValue();
7192 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7193 continue;
7194 }
7195 if (!printed) {
7196 pw.println(" mScreenCompatPackages:");
7197 printed = true;
7198 }
7199 pw.println(" " + pkg + ": " + mode);
7200 }
7201 }
7202 }
7203
7204 if (dumpPackage == null) {
7205 pw.println(" mWakefulness="
7206 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007207 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007208 if (mRunningVoice != null) {
7209 pw.println(" mRunningVoice=" + mRunningVoice);
7210 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7211 }
7212 pw.println(" mSleeping=" + mSleeping);
7213 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7214 pw.println(" mVrController=" + mVrController);
7215 }
7216 if (mCurAppTimeTracker != null) {
7217 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7218 }
7219 if (mAllowAppSwitchUids.size() > 0) {
7220 boolean printed = false;
7221 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7222 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7223 for (int j = 0; j < types.size(); j++) {
7224 if (dumpPackage == null ||
7225 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7226 if (needSep) {
7227 pw.println();
7228 needSep = false;
7229 }
7230 if (!printed) {
7231 pw.println(" mAllowAppSwitchUids:");
7232 printed = true;
7233 }
7234 pw.print(" User ");
7235 pw.print(mAllowAppSwitchUids.keyAt(i));
7236 pw.print(": Type ");
7237 pw.print(types.keyAt(j));
7238 pw.print(" = ");
7239 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7240 pw.println();
7241 }
7242 }
7243 }
7244 }
7245 if (dumpPackage == null) {
7246 if (mController != null) {
7247 pw.println(" mController=" + mController
7248 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7249 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007250 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7251 pw.println(" mLaunchingActivityWakeLock="
7252 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007253 }
7254
7255 return needSep;
7256 }
7257 }
7258
7259 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007260 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7261 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007262 synchronized (mGlobalLock) {
7263 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007264 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007265 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007266 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7267 if (mRunningVoice != null) {
7268 final long vrToken = proto.start(
7269 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7270 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7271 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007272 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007273 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7274 proto.end(vrToken);
7275 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007276 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007277 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007278 if (mController != null) {
7279 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007280 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7281 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007282 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7283 proto.end(token);
7284 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007285 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7286 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007287 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007288 }
7289
7290 if (mHomeProcess != null && (dumpPackage == null
7291 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007292 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007293 }
7294
7295 if (mPreviousProcess != null && (dumpPackage == null
7296 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007297 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007298 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7299 }
7300
7301 if (mHeavyWeightProcess != null && (dumpPackage == null
7302 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007303 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007304 }
7305
7306 for (Map.Entry<String, Integer> entry
7307 : mCompatModePackages.getPackages().entrySet()) {
7308 String pkg = entry.getKey();
7309 int mode = entry.getValue();
7310 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7311 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7312 proto.write(PACKAGE, pkg);
7313 proto.write(MODE, mode);
7314 proto.end(compatToken);
7315 }
7316 }
7317
7318 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007319 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007320 }
7321
7322 }
7323 }
7324
7325 @Override
7326 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7327 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7328 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007329 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7330 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007331 }
7332
7333 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007334 public void dumpForOom(PrintWriter pw) {
7335 synchronized (mGlobalLock) {
7336 pw.println(" mHomeProcess: " + mHomeProcess);
7337 pw.println(" mPreviousProcess: " + mPreviousProcess);
7338 if (mHeavyWeightProcess != null) {
7339 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7340 }
7341 }
7342 }
7343
7344 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007345 public boolean canGcNow() {
7346 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007347 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007348 }
7349 }
7350
Riddle Hsua0536432019-02-16 00:38:59 +08007351 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007352 @Override
7353 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007354 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007355 if (mRootWindowContainer == null) {
7356 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007357 // oomadj after AMS created.
7358 return null;
7359 }
Louis Chang149d5c82019-12-30 09:47:39 +08007360 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007361 return top != null ? top.app : null;
7362 }
7363 }
7364
Riddle Hsua0536432019-02-16 00:38:59 +08007365 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007366 @Override
7367 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007368 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007369 if (mRootWindowContainer != null) {
7370 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007371 }
7372 }
7373 }
7374
7375 @Override
7376 public void scheduleDestroyAllActivities(String reason) {
7377 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007378 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007379 }
7380 }
7381
7382 @Override
7383 public void removeUser(int userId) {
7384 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007385 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007386 }
7387 }
7388
7389 @Override
7390 public boolean switchUser(int userId, UserState userState) {
7391 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007392 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007393 }
7394 }
7395
7396 @Override
7397 public void onHandleAppCrash(WindowProcessController wpc) {
7398 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007399 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007400 }
7401 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007402
7403 @Override
7404 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7405 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007406 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007407 }
7408 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007409
Riddle Hsua0536432019-02-16 00:38:59 +08007410 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007411 @Override
7412 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007413 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007414 }
7415
Riddle Hsua0536432019-02-16 00:38:59 +08007416 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007417 @Override
7418 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007419 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007420 }
7421
Riddle Hsua0536432019-02-16 00:38:59 +08007422 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007423 @Override
7424 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007425 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007426 }
7427
Riddle Hsua0536432019-02-16 00:38:59 +08007428 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007429 @Override
7430 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007431 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007432 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007433
7434 @Override
7435 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007436 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007437 mPendingTempWhitelist.put(uid, tag);
7438 }
7439 }
7440
7441 @Override
7442 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007443 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007444 mPendingTempWhitelist.remove(uid);
7445 }
7446 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007447
7448 @Override
7449 public boolean handleAppCrashInActivityController(String processName, int pid,
7450 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7451 Runnable killCrashingAppCallback) {
7452 synchronized (mGlobalLock) {
7453 if (mController == null) {
7454 return false;
7455 }
7456
7457 try {
7458 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7459 stackTrace)) {
7460 killCrashingAppCallback.run();
7461 return true;
7462 }
7463 } catch (RemoteException e) {
7464 mController = null;
7465 Watchdog.getInstance().setActivityController(null);
7466 }
7467 return false;
7468 }
7469 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007470
7471 @Override
7472 public void removeRecentTasksByPackageName(String packageName, int userId) {
7473 synchronized (mGlobalLock) {
7474 mRecentTasks.removeTasksByPackageName(packageName, userId);
7475 }
7476 }
7477
7478 @Override
7479 public void cleanupRecentTasksForUser(int userId) {
7480 synchronized (mGlobalLock) {
7481 mRecentTasks.cleanupLocked(userId);
7482 }
7483 }
7484
7485 @Override
7486 public void loadRecentTasksForUser(int userId) {
7487 synchronized (mGlobalLock) {
7488 mRecentTasks.loadUserRecentsLocked(userId);
7489 }
7490 }
7491
7492 @Override
7493 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7494 synchronized (mGlobalLock) {
7495 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7496 }
7497 }
7498
7499 @Override
7500 public void flushRecentTasks() {
7501 mRecentTasks.flush();
7502 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007503
7504 @Override
7505 public WindowProcessController getHomeProcess() {
7506 synchronized (mGlobalLock) {
7507 return mHomeProcess;
7508 }
7509 }
7510
7511 @Override
7512 public WindowProcessController getPreviousProcess() {
7513 synchronized (mGlobalLock) {
7514 return mPreviousProcess;
7515 }
7516 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007517
7518 @Override
7519 public void clearLockedTasks(String reason) {
7520 synchronized (mGlobalLock) {
7521 getLockTaskController().clearLockedTasks(reason);
7522 }
7523 }
7524
7525 @Override
7526 public void updateUserConfiguration() {
7527 synchronized (mGlobalLock) {
7528 final Configuration configuration = new Configuration(getGlobalConfiguration());
7529 final int currentUserId = mAmInternal.getCurrentUserId();
7530 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7531 configuration, currentUserId, Settings.System.canWrite(mContext));
7532 updateConfigurationLocked(configuration, null /* starting */,
7533 false /* initLocale */, false /* persistent */, currentUserId,
7534 false /* deferResume */);
7535 }
7536 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007537
7538 @Override
7539 public boolean canShowErrorDialogs() {
7540 synchronized (mGlobalLock) {
7541 return mShowDialogs && !mSleeping && !mShuttingDown
7542 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7543 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7544 mAmInternal.getCurrentUserId())
7545 && !(UserManager.isDeviceInDemoMode(mContext)
7546 && mAmInternal.getCurrentUser().isDemo());
7547 }
7548 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007549
7550 @Override
7551 public void setProfileApp(String profileApp) {
7552 synchronized (mGlobalLock) {
7553 mProfileApp = profileApp;
7554 }
7555 }
7556
7557 @Override
7558 public void setProfileProc(WindowProcessController wpc) {
7559 synchronized (mGlobalLock) {
7560 mProfileProc = wpc;
7561 }
7562 }
7563
7564 @Override
7565 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7566 synchronized (mGlobalLock) {
7567 mProfilerInfo = profilerInfo;
7568 }
7569 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007570
7571 @Override
7572 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7573 synchronized (mGlobalLock) {
7574 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7575 }
7576 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007577
7578 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007579 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7580 boolean reducedResolution) {
7581 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7582 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007583 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007584
7585 @Override
7586 public boolean isUidForeground(int uid) {
7587 synchronized (mGlobalLock) {
7588 return ActivityTaskManagerService.this.isUidForeground(uid);
7589 }
7590 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007591
7592 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007593 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007594 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007595 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007596 }
7597 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007598
7599 @Override
7600 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007601 // Translate package names into UIDs
7602 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007603 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007604 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7605 if (uid >= 0) {
7606 result.add(uid);
7607 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007608 }
7609 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007610 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007611 }
7612 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007613 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007614}