blob: 8491bc2c4756f46afc31725455f334f9dd54e7c5 [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 =
1615 r.getActivityStack().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 Ogunwale8b19de92018-11-29 19:58:26 -08002040 r.getActivityStack().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) {
Louis Chang149d5c82019-12-30 09:47:39 +08002076 return mRootWindowContainer.getStackInfo(focusedStack.mStackId);
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 Ogunwale8b19de92018-11-29 19:58:26 -08002178 return srec.getActivityStack().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 Ogunwalea38654f2019-11-17 20:37:15 -08002191 return r.getActivityStack().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 }
2357 ActivityStack stack = r.getActivityStack();
2358 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.
2585 r.getActivityStack().forAllActivities(c);
2586 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 Ogunwale8b19de92018-11-29 19:58:26 -08003218 final ActivityStack stack = r.getActivityStack();
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 Rosky226de132020-01-03 18:00:29 -08003306 private int sanitizeAndApplyChange(ConfigurationContainer 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 Rosky226de132020-01-03 18:00:29 -08003350 private int applyWindowContainerChange(ConfigurationContainer cc,
Robert Carr8a2f9132019-11-11 15:03:15 -08003351 WindowContainerTransaction.Change c) {
Evan Rosky226de132020-01-03 18:00:29 -08003352 int effects = sanitizeAndApplyChange(cc, c);
Robert Carr8a2f9132019-11-11 15:03:15 -08003353
3354 Rect enterPipBounds = c.getEnterPipBounds();
3355 if (enterPipBounds != null) {
3356 Task tr = (Task) cc;
3357 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();
3381 final ConfigurationContainer cc =
3382 ConfigurationContainer.RemoteToken.fromBinder(
3383 entry.getKey()).getContainer();
3384 int containerEffect = applyWindowContainerChange(cc, entry.getValue());
3385 effects |= containerEffect;
3386 // Lifecycle changes will trigger ensureConfig for everything.
3387 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) == 0
3388 && (containerEffect & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
3389 if (cc instanceof WindowContainer) {
3390 haveConfigChanges.add((WindowContainer) cc);
3391 }
3392 }
3393 }
3394 if ((effects & TRANSACT_EFFECTS_LIFECYCLE) != 0) {
3395 // Already calls ensureActivityConfig
3396 mRootWindowContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS);
3397 } else if ((effects & TRANSACT_EFFECTS_CLIENT_CONFIG) != 0) {
3398 final PooledConsumer f = PooledLambda.obtainConsumer(
3399 ActivityRecord::ensureActivityConfiguration,
3400 PooledLambda.__(ActivityRecord.class), 0,
3401 false /* preserveWindow */);
3402 try {
3403 for (int i = haveConfigChanges.size() - 1; i >= 0; --i) {
3404 haveConfigChanges.valueAt(i).forAllActivities(f);
3405 }
3406 } finally {
3407 f.recycle();
3408 }
3409 }
3410 } finally {
3411 continueWindowLayout();
Evan Roskyddedfd42019-10-04 13:38:38 -07003412 }
3413 }
3414 } finally {
3415 Binder.restoreCallingIdentity(ident);
3416 }
3417 }
3418
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003419 @Override
3420 public boolean releaseActivityInstance(IBinder token) {
3421 synchronized (mGlobalLock) {
3422 final long origId = Binder.clearCallingIdentity();
3423 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003424 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3425 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 return false;
3427 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003428 r.destroyImmediately(true /* removeFromApp */, "app-req");
3429 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 } finally {
3431 Binder.restoreCallingIdentity(origId);
3432 }
3433 }
3434 }
3435
3436 @Override
3437 public void releaseSomeActivities(IApplicationThread appInt) {
3438 synchronized (mGlobalLock) {
3439 final long origId = Binder.clearCallingIdentity();
3440 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003441 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003442 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 } finally {
3444 Binder.restoreCallingIdentity(origId);
3445 }
3446 }
3447 }
3448
3449 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003450 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003451 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003452 != PackageManager.PERMISSION_GRANTED) {
3453 throw new SecurityException("Requires permission "
3454 + android.Manifest.permission.DEVICE_POWER);
3455 }
3456
3457 synchronized (mGlobalLock) {
3458 long ident = Binder.clearCallingIdentity();
3459 if (mKeyguardShown != keyguardShowing) {
3460 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003461 final Message msg = PooledLambda.obtainMessage(
3462 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3463 keyguardShowing);
3464 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003465 }
3466 try {
wilsonshih177261f2019-02-22 12:02:18 +08003467 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 } finally {
3469 Binder.restoreCallingIdentity(ident);
3470 }
3471 }
3472
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003473 mH.post(() -> {
3474 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3475 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3476 }
3477 });
3478 }
3479
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003480 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 mH.post(() -> {
3482 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3483 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3484 }
3485 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003486 }
3487
3488 @Override
3489 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003490 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3491 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003492
3493 final File passedIconFile = new File(filePath);
3494 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3495 passedIconFile.getName());
3496 if (!legitIconFile.getPath().equals(filePath)
3497 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3498 throw new IllegalArgumentException("Bad file path: " + filePath
3499 + " passed for userId " + userId);
3500 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003501 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 }
3503
3504 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 synchronized (mGlobalLock) {
3508 final long ident = Binder.clearCallingIdentity();
3509 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003510 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 if (stack == null) {
3512 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3513 return;
3514 }
3515 if (!stack.isActivityTypeStandardOrUndefined()) {
3516 throw new IllegalArgumentException(
3517 "Removing non-standard stack is not allowed.");
3518 }
3519 mStackSupervisor.removeStack(stack);
3520 } finally {
3521 Binder.restoreCallingIdentity(ident);
3522 }
3523 }
3524 }
3525
3526 @Override
3527 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003528 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003529
3530 synchronized (mGlobalLock) {
3531 final long ident = Binder.clearCallingIdentity();
3532 try {
3533 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3534 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003535 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003536 } finally {
3537 Binder.restoreCallingIdentity(ident);
3538 }
3539 }
3540 }
3541
3542 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003543 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003544 synchronized (mGlobalLock) {
3545 long ident = Binder.clearCallingIdentity();
3546 try {
3547 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3548 if (r == null) {
3549 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003550 "toggleFreeformWindowingMode: No activity record matching token="
3551 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 }
3553
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003554 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003555 if (stack == null) {
3556 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3557 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 }
3559
Yunfan Chend967af82019-01-17 18:30:18 +09003560 if (!stack.inFreeformWindowingMode()
3561 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3562 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3563 + "toggle between fullscreen and freeform.");
3564 }
3565
3566 if (stack.inFreeformWindowingMode()) {
3567 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003568 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003569 throw new IllegalStateException("Size-compat windows are currently not"
3570 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003571 } else if (stack.getParent().inFreeformWindowingMode()) {
3572 // If the window is on a freeform display, set it to undefined. It will be
3573 // resolved to freeform and it can adjust windowing mode when the display mode
3574 // changes in runtime.
3575 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003576 } else {
3577 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3578 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579 } finally {
3580 Binder.restoreCallingIdentity(ident);
3581 }
3582 }
3583 }
3584
3585 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3586 @Override
3587 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003588 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003590 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 }
3592
3593 /** Unregister a task stack listener so that it stops receiving callbacks. */
3594 @Override
3595 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003596 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003597 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003598 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003599 }
3600
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 @Override
3602 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3603 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3604 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3605 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3606 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3607 }
3608
3609 @Override
3610 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3611 IBinder activityToken, int flags) {
3612 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3613 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3614 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3615 }
3616
3617 @Override
3618 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3619 Bundle args) {
3620 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3621 true /* focused */, true /* newSessionId */, userHandle, args,
3622 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3623 }
3624
3625 @Override
3626 public Bundle getAssistContextExtras(int requestType) {
3627 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3628 null, null, true /* focused */, true /* newSessionId */,
3629 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3630 if (pae == null) {
3631 return null;
3632 }
3633 synchronized (pae) {
3634 while (!pae.haveResult) {
3635 try {
3636 pae.wait();
3637 } catch (InterruptedException e) {
3638 }
3639 }
3640 }
3641 synchronized (mGlobalLock) {
3642 buildAssistBundleLocked(pae, pae.result);
3643 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003644 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 }
3646 return pae.extras;
3647 }
3648
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003649 /**
3650 * Binder IPC calls go through the public entry point.
3651 * This can be called with or without the global lock held.
3652 */
3653 private static int checkCallingPermission(String permission) {
3654 return checkPermission(
3655 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3656 }
3657
3658 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003659 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003660 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3661 mAmInternal.enforceCallingPermission(permission, func);
3662 }
3663 }
3664
3665 @VisibleForTesting
3666 int checkGetTasksPermission(String permission, int pid, int uid) {
3667 return checkPermission(permission, pid, uid);
3668 }
3669
3670 static int checkPermission(String permission, int pid, int uid) {
3671 if (permission == null) {
3672 return PackageManager.PERMISSION_DENIED;
3673 }
3674 return checkComponentPermission(permission, pid, uid, -1, true);
3675 }
3676
Wale Ogunwale214f3482018-10-04 11:00:47 -07003677 public static int checkComponentPermission(String permission, int pid, int uid,
3678 int owningUid, boolean exported) {
3679 return ActivityManagerService.checkComponentPermission(
3680 permission, pid, uid, owningUid, exported);
3681 }
3682
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003683 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3684 if (getRecentTasks().isCallerRecents(callingUid)) {
3685 // Always allow the recents component to get tasks
3686 return true;
3687 }
3688
3689 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3690 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3691 if (!allowed) {
3692 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3693 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3694 // Temporary compatibility: some existing apps on the system image may
3695 // still be requesting the old permission and not switched to the new
3696 // one; if so, we'll still allow them full access. This means we need
3697 // to see if they are holding the old permission and are a system app.
3698 try {
3699 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3700 allowed = true;
3701 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3702 + " is using old GET_TASKS but privileged; allowing");
3703 }
3704 } catch (RemoteException e) {
3705 }
3706 }
3707 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3708 + " does not hold REAL_GET_TASKS; limiting output");
3709 }
3710 return allowed;
3711 }
3712
Nicholas Sauer0259e532019-08-30 08:24:55 -07003713 boolean isCrossUserAllowed(int pid, int uid) {
3714 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3715 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3716 }
3717
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3719 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3720 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3721 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003722 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003723 "enqueueAssistContext()");
3724
3725 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003726 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003727 if (activity == null) {
3728 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3729 return null;
3730 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003731 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003732 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3733 return null;
3734 }
3735 if (focused) {
3736 if (activityToken != null) {
3737 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3738 if (activity != caller) {
3739 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3740 + " is not current top " + activity);
3741 return null;
3742 }
3743 }
3744 } else {
3745 activity = ActivityRecord.forTokenLocked(activityToken);
3746 if (activity == null) {
3747 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3748 + " couldn't be found");
3749 return null;
3750 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003751 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003752 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3753 return null;
3754 }
3755 }
3756
3757 PendingAssistExtras pae;
3758 Bundle extras = new Bundle();
3759 if (args != null) {
3760 extras.putAll(args);
3761 }
3762 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003763 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003764
3765 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3766 userHandle);
3767 pae.isHome = activity.isActivityTypeHome();
3768
3769 // Increment the sessionId if necessary
3770 if (newSessionId) {
3771 mViSessionId++;
3772 }
3773 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003774 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3775 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003776 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003777 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003778 } catch (RemoteException e) {
3779 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3780 return null;
3781 }
3782 return pae;
3783 }
3784 }
3785
3786 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3787 if (result != null) {
3788 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3789 }
3790 if (pae.hint != null) {
3791 pae.extras.putBoolean(pae.hint, true);
3792 }
3793 }
3794
3795 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3796 IAssistDataReceiver receiver;
3797 synchronized (mGlobalLock) {
3798 mPendingAssistExtras.remove(pae);
3799 receiver = pae.receiver;
3800 }
3801 if (receiver != null) {
3802 // Caller wants result sent back to them.
3803 Bundle sendBundle = new Bundle();
3804 // At least return the receiver extras
3805 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3806 try {
3807 pae.receiver.onHandleAssistData(sendBundle);
3808 } catch (RemoteException e) {
3809 }
3810 }
3811 }
3812
3813 public class PendingAssistExtras extends Binder implements Runnable {
3814 public final ActivityRecord activity;
3815 public boolean isHome;
3816 public final Bundle extras;
3817 public final Intent intent;
3818 public final String hint;
3819 public final IAssistDataReceiver receiver;
3820 public final int userHandle;
3821 public boolean haveResult = false;
3822 public Bundle result = null;
3823 public AssistStructure structure = null;
3824 public AssistContent content = null;
3825 public Bundle receiverExtras;
3826
3827 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3828 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3829 int _userHandle) {
3830 activity = _activity;
3831 extras = _extras;
3832 intent = _intent;
3833 hint = _hint;
3834 receiver = _receiver;
3835 receiverExtras = _receiverExtras;
3836 userHandle = _userHandle;
3837 }
3838
3839 @Override
3840 public void run() {
3841 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3842 synchronized (this) {
3843 haveResult = true;
3844 notifyAll();
3845 }
3846 pendingAssistExtrasTimedOut(this);
3847 }
3848 }
3849
3850 @Override
3851 public boolean isAssistDataAllowedOnCurrentActivity() {
3852 int userId;
3853 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003854 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3856 return false;
3857 }
3858
Wale Ogunwale21e06482019-11-18 05:14:15 -08003859 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003860 if (activity == null) {
3861 return false;
3862 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003863 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 }
3865 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3866 }
3867
3868 @Override
3869 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3870 long ident = Binder.clearCallingIdentity();
3871 try {
3872 synchronized (mGlobalLock) {
3873 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003874 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875 if (top != caller) {
3876 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3877 + " is not current top " + top);
3878 return false;
3879 }
3880 if (!top.nowVisible) {
3881 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3882 + " is not visible");
3883 return false;
3884 }
3885 }
3886 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3887 token);
3888 } finally {
3889 Binder.restoreCallingIdentity(ident);
3890 }
3891 }
3892
3893 @Override
3894 public boolean isRootVoiceInteraction(IBinder token) {
3895 synchronized (mGlobalLock) {
3896 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3897 if (r == null) {
3898 return false;
3899 }
3900 return r.rootVoiceInteraction;
3901 }
3902 }
3903
Wale Ogunwalef6733932018-06-27 05:14:34 -07003904 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3905 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3906 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3907 if (activityToCallback == null) return;
3908 activityToCallback.setVoiceSessionLocked(voiceSession);
3909
3910 // Inform the activity
3911 try {
3912 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3913 voiceInteractor);
3914 long token = Binder.clearCallingIdentity();
3915 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003916 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003917 } finally {
3918 Binder.restoreCallingIdentity(token);
3919 }
3920 // TODO: VI Should we cache the activity so that it's easier to find later
3921 // rather than scan through all the stacks and activities?
3922 } catch (RemoteException re) {
3923 activityToCallback.clearVoiceSessionLocked();
3924 // TODO: VI Should this terminate the voice session?
3925 }
3926 }
3927
3928 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3929 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3930 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3931 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3932 boolean wasRunningVoice = mRunningVoice != null;
3933 mRunningVoice = session;
3934 if (!wasRunningVoice) {
3935 mVoiceWakeLock.acquire();
3936 updateSleepIfNeededLocked();
3937 }
3938 }
3939 }
3940
3941 void finishRunningVoiceLocked() {
3942 if (mRunningVoice != null) {
3943 mRunningVoice = null;
3944 mVoiceWakeLock.release();
3945 updateSleepIfNeededLocked();
3946 }
3947 }
3948
3949 @Override
3950 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3951 synchronized (mGlobalLock) {
3952 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3953 if (keepAwake) {
3954 mVoiceWakeLock.acquire();
3955 } else {
3956 mVoiceWakeLock.release();
3957 }
3958 }
3959 }
3960 }
3961
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 @Override
3963 public ComponentName getActivityClassForToken(IBinder token) {
3964 synchronized (mGlobalLock) {
3965 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3966 if (r == null) {
3967 return null;
3968 }
3969 return r.intent.getComponent();
3970 }
3971 }
3972
3973 @Override
3974 public String getPackageForToken(IBinder token) {
3975 synchronized (mGlobalLock) {
3976 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3977 if (r == null) {
3978 return null;
3979 }
3980 return r.packageName;
3981 }
3982 }
3983
3984 @Override
3985 public void showLockTaskEscapeMessage(IBinder token) {
3986 synchronized (mGlobalLock) {
3987 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3988 if (r == null) {
3989 return;
3990 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003991 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 }
3993 }
3994
3995 @Override
3996 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003997 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 final long token = Binder.clearCallingIdentity();
3999 try {
4000 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004001 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002 }
4003 } finally {
4004 Binder.restoreCallingIdentity(token);
4005 }
4006 }
4007
4008 /**
4009 * Try to place task to provided position. The final position might be different depending on
4010 * current user and stacks state. The task will be moved to target stack if it's currently in
4011 * different stack.
4012 */
4013 @Override
4014 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004015 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004016 synchronized (mGlobalLock) {
4017 long ident = Binder.clearCallingIdentity();
4018 try {
4019 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
4020 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08004021 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 if (task == null) {
4023 throw new IllegalArgumentException("positionTaskInStack: no task for id="
4024 + taskId);
4025 }
4026
Louis Chang149d5c82019-12-30 09:47:39 +08004027 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028
4029 if (stack == null) {
4030 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
4031 + stackId);
4032 }
4033 if (!stack.isActivityTypeStandardOrUndefined()) {
4034 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
4035 + " the position of task " + taskId + " in/to non-standard stack");
4036 }
4037
4038 // TODO: Have the callers of this API call a separate reparent method if that is
4039 // what they intended to do vs. having this method also do reparenting.
4040 if (task.getStack() == stack) {
4041 // Change position in current stack.
4042 stack.positionChildAt(task, position);
4043 } else {
4044 // Reparent to new stack.
4045 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4046 !DEFER_RESUME, "positionTaskInStack");
4047 }
4048 } finally {
4049 Binder.restoreCallingIdentity(ident);
4050 }
4051 }
4052 }
4053
4054 @Override
4055 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4056 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4057 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004058 + Arrays.toString(horizontalSizeConfiguration) + " "
4059 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 synchronized (mGlobalLock) {
4061 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4062 if (record == null) {
4063 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4064 + "found for: " + token);
4065 }
4066 record.setSizeConfigurations(horizontalSizeConfiguration,
4067 verticalSizeConfigurations, smallestSizeConfigurations);
4068 }
4069 }
4070
4071 /**
4072 * Dismisses split-screen multi-window mode.
4073 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4074 */
4075 @Override
4076 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004077 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4079 final long ident = Binder.clearCallingIdentity();
4080 try {
4081 synchronized (mGlobalLock) {
4082 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004083 mRootWindowContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004084 if (stack == null) {
4085 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4086 return;
4087 }
4088
4089 if (toTop) {
4090 // Caller wants the current split-screen primary stack to be the top stack after
4091 // it goes fullscreen, so move it to the front.
4092 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004093 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004094 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004095 // stack after it goes fullscreen, so we move the focus to the top-most
4096 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004097 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4098 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4099 if (otherStack != null) {
4100 otherStack.moveToFront("dismissSplitScreenMode_other");
4101 }
4102 }
4103
Evan Rosky10475742018-09-05 19:02:48 -07004104 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004105 }
4106 } finally {
4107 Binder.restoreCallingIdentity(ident);
4108 }
4109 }
4110
4111 /**
4112 * Dismisses Pip
4113 * @param animate True if the dismissal should be animated.
4114 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4115 * default animation duration should be used.
4116 */
4117 @Override
4118 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004119 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 final long ident = Binder.clearCallingIdentity();
4121 try {
4122 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004123 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004124 mRootWindowContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 if (stack == null) {
4126 Slog.w(TAG, "dismissPip: pinned stack not found.");
4127 return;
4128 }
4129 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4130 throw new IllegalArgumentException("Stack: " + stack
4131 + " doesn't support animated resize.");
4132 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004133 /**
4134 * TODO(b/146594635): Remove all PIP animation code from WM
4135 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4136 */
4137 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004138 stack.animateResizePinnedStack(null /* destBounds */,
4139 null /* sourceHintBounds */, animationDuration,
4140 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004141 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004142 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 }
4144 }
4145 } finally {
4146 Binder.restoreCallingIdentity(ident);
4147 }
4148 }
4149
4150 @Override
4151 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004152 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004153 synchronized (mGlobalLock) {
4154 mSuppressResizeConfigChanges = suppress;
4155 }
4156 }
4157
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 @Override
4159 // TODO: API should just be about changing windowing modes...
4160 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004161 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 "moveTasksToFullscreenStack()");
4163 synchronized (mGlobalLock) {
4164 final long origId = Binder.clearCallingIdentity();
4165 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004166 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 if (stack != null){
4168 if (!stack.isActivityTypeStandardOrUndefined()) {
4169 throw new IllegalArgumentException(
4170 "You can't move tasks from non-standard stacks.");
4171 }
4172 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4173 }
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177 }
4178 }
4179
4180 /**
4181 * Moves the top activity in the input stackId to the pinned stack.
4182 *
4183 * @param stackId Id of stack to move the top activity to pinned stack.
4184 * @param bounds Bounds to use for pinned stack.
4185 *
4186 * @return True if the top activity of the input stack was successfully moved to the pinned
4187 * stack.
4188 */
4189 @Override
4190 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 "moveTopActivityToPinnedStack()");
4193 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004194 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4196 + "Device doesn't support picture-in-picture mode");
4197 }
4198
4199 long ident = Binder.clearCallingIdentity();
4200 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004201 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 } finally {
4203 Binder.restoreCallingIdentity(ident);
4204 }
4205 }
4206 }
4207
4208 @Override
4209 public boolean isInMultiWindowMode(IBinder token) {
4210 final long origId = Binder.clearCallingIdentity();
4211 try {
4212 synchronized (mGlobalLock) {
4213 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4214 if (r == null) {
4215 return false;
4216 }
4217 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4218 return r.inMultiWindowMode();
4219 }
4220 } finally {
4221 Binder.restoreCallingIdentity(origId);
4222 }
4223 }
4224
4225 @Override
4226 public boolean isInPictureInPictureMode(IBinder token) {
4227 final long origId = Binder.clearCallingIdentity();
4228 try {
4229 synchronized (mGlobalLock) {
4230 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4231 }
4232 } finally {
4233 Binder.restoreCallingIdentity(origId);
4234 }
4235 }
4236
4237 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004238 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4239 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240 return false;
4241 }
4242
4243 // If we are animating to fullscreen then we have already dispatched the PIP mode
4244 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004245 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004246 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 }
4248
4249 @Override
4250 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4251 final long origId = Binder.clearCallingIdentity();
4252 try {
4253 synchronized (mGlobalLock) {
4254 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4255 "enterPictureInPictureMode", token, params);
4256
4257 // If the activity is already in picture in picture mode, then just return early
4258 if (isInPictureInPictureMode(r)) {
4259 return true;
4260 }
4261
4262 // Activity supports picture-in-picture, now check that we can enter PiP at this
4263 // point, if it is
4264 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4265 false /* beforeStopping */)) {
4266 return false;
4267 }
4268
4269 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004270 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004271 if (r.getParent() == null) {
4272 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4273 return;
4274 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004275 // Only update the saved args from the args that are set
4276 r.pictureInPictureArgs.copyOnlySet(params);
4277 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4278 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4279 // Adjust the source bounds by the insets for the transition down
4280 final Rect sourceBounds = new Rect(
4281 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004282 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004283 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004284 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004285 stack.setPictureInPictureAspectRatio(aspectRatio);
4286 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004287 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4288 r.info.applicationInfo.uid, r.shortComponentName,
4289 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004290 logPictureInPictureArgs(params);
4291 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 };
4293
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004294 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004295 // If the keyguard is showing or occluded, then try and dismiss it before
4296 // entering picture-in-picture (this will prompt the user to authenticate if the
4297 // device is currently locked).
4298 dismissKeyguard(token, new KeyguardDismissCallback() {
4299 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004300 public void onDismissSucceeded() {
4301 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 }
4303 }, null /* message */);
4304 } else {
4305 // Enter picture in picture immediately otherwise
4306 enterPipRunnable.run();
4307 }
4308 return true;
4309 }
4310 } finally {
4311 Binder.restoreCallingIdentity(origId);
4312 }
4313 }
4314
4315 @Override
4316 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4317 final long origId = Binder.clearCallingIdentity();
4318 try {
4319 synchronized (mGlobalLock) {
4320 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4321 "setPictureInPictureParams", token, params);
4322
4323 // Only update the saved args from the args that are set
4324 r.pictureInPictureArgs.copyOnlySet(params);
4325 if (r.inPinnedWindowingMode()) {
4326 // If the activity is already in picture-in-picture, update the pinned stack now
4327 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4328 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004329 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 if (!stack.isAnimatingBoundsToFullscreen()) {
4331 stack.setPictureInPictureAspectRatio(
4332 r.pictureInPictureArgs.getAspectRatio());
4333 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4334 }
4335 }
4336 logPictureInPictureArgs(params);
4337 }
4338 } finally {
4339 Binder.restoreCallingIdentity(origId);
4340 }
4341 }
4342
4343 @Override
4344 public int getMaxNumPictureInPictureActions(IBinder token) {
4345 // Currently, this is a static constant, but later, we may change this to be dependent on
4346 // the context of the activity
4347 return 3;
4348 }
4349
4350 private void logPictureInPictureArgs(PictureInPictureParams params) {
4351 if (params.hasSetActions()) {
4352 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4353 params.getActions().size());
4354 }
4355 if (params.hasSetAspectRatio()) {
4356 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4357 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4358 MetricsLogger.action(lm);
4359 }
4360 }
4361
4362 /**
4363 * Checks the state of the system and the activity associated with the given {@param token} to
4364 * verify that picture-in-picture is supported for that activity.
4365 *
4366 * @return the activity record for the given {@param token} if all the checks pass.
4367 */
4368 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4369 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004370 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 throw new IllegalStateException(caller
4372 + ": Device doesn't support picture-in-picture mode.");
4373 }
4374
4375 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4376 if (r == null) {
4377 throw new IllegalStateException(caller
4378 + ": Can't find activity for token=" + token);
4379 }
4380
4381 if (!r.supportsPictureInPicture()) {
4382 throw new IllegalStateException(caller
4383 + ": Current activity does not support picture-in-picture.");
4384 }
4385
4386 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004387 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004388 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 final float minAspectRatio = mContext.getResources().getFloat(
4390 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4391 final float maxAspectRatio = mContext.getResources().getFloat(
4392 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4393 throw new IllegalArgumentException(String.format(caller
4394 + ": Aspect ratio is too extreme (must be between %f and %f).",
4395 minAspectRatio, maxAspectRatio));
4396 }
4397
4398 // Truncate the number of actions if necessary
4399 params.truncateActions(getMaxNumPictureInPictureActions(token));
4400
4401 return r;
4402 }
4403
4404 @Override
4405 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 synchronized (mGlobalLock) {
4408 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4409 if (r == null) {
4410 throw new IllegalArgumentException("Activity does not exist; token="
4411 + activityToken);
4412 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004413 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004414 }
4415 }
4416
4417 @Override
4418 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4419 Rect tempDockedTaskInsetBounds,
4420 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 long ident = Binder.clearCallingIdentity();
4423 try {
4424 synchronized (mGlobalLock) {
4425 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4426 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4427 PRESERVE_WINDOWS);
4428 }
4429 } finally {
4430 Binder.restoreCallingIdentity(ident);
4431 }
4432 }
4433
4434 @Override
4435 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004436 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437 final long ident = Binder.clearCallingIdentity();
4438 try {
4439 synchronized (mGlobalLock) {
4440 mStackSupervisor.setSplitScreenResizing(resizing);
4441 }
4442 } finally {
4443 Binder.restoreCallingIdentity(ident);
4444 }
4445 }
4446
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 /**
4448 * Check that we have the features required for VR-related API calls, and throw an exception if
4449 * not.
4450 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004451 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 if (!mContext.getPackageManager().hasSystemFeature(
4453 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4454 throw new UnsupportedOperationException("VR mode not supported on this device!");
4455 }
4456 }
4457
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 @Override
4459 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004460 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461
4462 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4463
4464 ActivityRecord r;
4465 synchronized (mGlobalLock) {
4466 r = ActivityRecord.isInStackLocked(token);
4467 }
4468
4469 if (r == null) {
4470 throw new IllegalArgumentException();
4471 }
4472
4473 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004474 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004475 VrManagerInternal.NO_ERROR) {
4476 return err;
4477 }
4478
4479 // Clear the binder calling uid since this path may call moveToTask().
4480 final long callingId = Binder.clearCallingIdentity();
4481 try {
4482 synchronized (mGlobalLock) {
4483 r.requestedVrComponent = (enabled) ? packageName : null;
4484
4485 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004486 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004487 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 }
4489 return 0;
4490 }
4491 } finally {
4492 Binder.restoreCallingIdentity(callingId);
4493 }
4494 }
4495
4496 @Override
4497 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4498 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4499 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004500 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4502 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4503 }
Louis Changcdec0802019-11-11 11:45:07 +08004504 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 || activity.voiceSession != null) {
4506 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4507 return;
4508 }
4509 if (activity.pendingVoiceInteractionStart) {
4510 Slog.w(TAG, "Pending start of voice interaction already.");
4511 return;
4512 }
4513 activity.pendingVoiceInteractionStart = true;
4514 }
4515 LocalServices.getService(VoiceInteractionManagerInternal.class)
4516 .startLocalVoiceInteraction(callingActivity, options);
4517 }
4518
4519 @Override
4520 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4521 LocalServices.getService(VoiceInteractionManagerInternal.class)
4522 .stopLocalVoiceInteraction(callingActivity);
4523 }
4524
4525 @Override
4526 public boolean supportsLocalVoiceInteraction() {
4527 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4528 .supportsLocalVoiceInteraction();
4529 }
4530
4531 /** Notifies all listeners when the pinned stack animation starts. */
4532 @Override
4533 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004534 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004535 }
4536
4537 /** Notifies all listeners when the pinned stack animation ends. */
4538 @Override
4539 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004540 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004541 }
4542
4543 @Override
4544 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004545 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004546 final long ident = Binder.clearCallingIdentity();
4547 try {
4548 synchronized (mGlobalLock) {
4549 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4550 }
4551 } finally {
4552 Binder.restoreCallingIdentity(ident);
4553 }
4554 }
4555
4556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004558 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559
4560 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004561 if (mWindowManager == null) {
4562 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4563 return false;
4564 }
4565
4566 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004568 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004569 }
4570
Riddle Hsua0022cd2019-09-09 21:12:41 +08004571 mH.sendMessage(PooledLambda.obtainMessage(
4572 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4573 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004574
4575 final long origId = Binder.clearCallingIdentity();
4576 try {
4577 if (values != null) {
4578 Settings.System.clearConfiguration(values);
4579 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004580 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 UserHandle.USER_NULL, false /* deferResume */,
4582 mTmpUpdateConfigurationResult);
4583 return mTmpUpdateConfigurationResult.changes != 0;
4584 } finally {
4585 Binder.restoreCallingIdentity(origId);
4586 }
4587 }
4588 }
4589
4590 @Override
4591 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4592 CharSequence message) {
4593 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004594 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4596 }
4597 final long callingId = Binder.clearCallingIdentity();
4598 try {
4599 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004600 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 }
4602 } finally {
4603 Binder.restoreCallingIdentity(callingId);
4604 }
4605 }
4606
4607 @Override
4608 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004609 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004610 "cancelTaskWindowTransition()");
4611 final long ident = Binder.clearCallingIdentity();
4612 try {
4613 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004614 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 MATCH_TASK_IN_STACKS_ONLY);
4616 if (task == null) {
4617 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4618 return;
4619 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004620 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004621 }
4622 } finally {
4623 Binder.restoreCallingIdentity(ident);
4624 }
4625 }
4626
4627 @Override
4628 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004629 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 final long ident = Binder.clearCallingIdentity();
4631 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004632 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004633 } finally {
4634 Binder.restoreCallingIdentity(ident);
4635 }
4636 }
4637
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004638 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4639 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004640 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004641 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004642 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004643 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4644 if (task == null) {
4645 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4646 return null;
4647 }
4648 }
4649 // Don't call this while holding the lock as this operation might hit the disk.
4650 return task.getSnapshot(reducedResolution, restoreFromDisk);
4651 }
4652
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004653 @Override
4654 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4655 synchronized (mGlobalLock) {
4656 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4657 if (r == null) {
4658 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4659 + token);
4660 return;
4661 }
4662 final long origId = Binder.clearCallingIdentity();
4663 try {
4664 r.setDisablePreviewScreenshots(disable);
4665 } finally {
4666 Binder.restoreCallingIdentity(origId);
4667 }
4668 }
4669 }
4670
Riddle Hsu440f88b2019-11-06 22:17:35 +08004671 @Override
4672 public void invalidateHomeTaskSnapshot(IBinder token) {
4673 synchronized (mGlobalLock) {
4674 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4675 if (r == null || !r.isActivityTypeHome()) {
4676 return;
4677 }
4678 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4679 }
4680 }
4681
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004682 /** Return the user id of the last resumed activity. */
4683 @Override
4684 public @UserIdInt
4685 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004686 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004687 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4688 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004689 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004690 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004691 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004692 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004693 }
4694 }
4695
4696 @Override
4697 public void updateLockTaskFeatures(int userId, int flags) {
4698 final int callingUid = Binder.getCallingUid();
4699 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004700 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004701 "updateLockTaskFeatures()");
4702 }
4703 synchronized (mGlobalLock) {
4704 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4705 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004706 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004707 }
4708 }
4709
4710 @Override
4711 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4712 synchronized (mGlobalLock) {
4713 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4714 if (r == null) {
4715 return;
4716 }
4717 final long origId = Binder.clearCallingIdentity();
4718 try {
4719 r.setShowWhenLocked(showWhenLocked);
4720 } finally {
4721 Binder.restoreCallingIdentity(origId);
4722 }
4723 }
4724 }
4725
4726 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004727 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4728 synchronized (mGlobalLock) {
4729 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4730 if (r == null) {
4731 return;
4732 }
4733 final long origId = Binder.clearCallingIdentity();
4734 try {
4735 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4736 } finally {
4737 Binder.restoreCallingIdentity(origId);
4738 }
4739 }
4740 }
4741
4742 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004743 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4744 synchronized (mGlobalLock) {
4745 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4746 if (r == null) {
4747 return;
4748 }
4749 final long origId = Binder.clearCallingIdentity();
4750 try {
4751 r.setTurnScreenOn(turnScreenOn);
4752 } finally {
4753 Binder.restoreCallingIdentity(origId);
4754 }
4755 }
4756 }
4757
4758 @Override
4759 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004760 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004761 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004762 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004763 synchronized (mGlobalLock) {
4764 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4765 if (r == null) {
4766 return;
4767 }
4768 final long origId = Binder.clearCallingIdentity();
4769 try {
4770 r.registerRemoteAnimations(definition);
4771 } finally {
4772 Binder.restoreCallingIdentity(origId);
4773 }
4774 }
4775 }
4776
4777 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004778 public void unregisterRemoteAnimations(IBinder token) {
4779 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4780 "unregisterRemoteAnimations");
4781 synchronized (mGlobalLock) {
4782 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4783 if (r == null) {
4784 return;
4785 }
4786 final long origId = Binder.clearCallingIdentity();
4787 try {
4788 r.unregisterRemoteAnimations();
4789 } finally {
4790 Binder.restoreCallingIdentity(origId);
4791 }
4792 }
4793 }
4794
4795 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004796 public void registerRemoteAnimationForNextActivityStart(String packageName,
4797 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004798 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004799 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004800 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004801 synchronized (mGlobalLock) {
4802 final long origId = Binder.clearCallingIdentity();
4803 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004804 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004805 packageName, adapter);
4806 } finally {
4807 Binder.restoreCallingIdentity(origId);
4808 }
4809 }
4810 }
4811
Evan Rosky966759f2019-01-15 10:33:58 -08004812 @Override
4813 public void registerRemoteAnimationsForDisplay(int displayId,
4814 RemoteAnimationDefinition definition) {
4815 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4816 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004817 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004818 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004819 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004820 if (display == null) {
4821 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4822 return;
4823 }
4824 final long origId = Binder.clearCallingIdentity();
4825 try {
4826 display.mDisplayContent.registerRemoteAnimations(definition);
4827 } finally {
4828 Binder.restoreCallingIdentity(origId);
4829 }
4830 }
4831 }
4832
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004833 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4834 @Override
4835 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4836 synchronized (mGlobalLock) {
4837 final long origId = Binder.clearCallingIdentity();
4838 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004839 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004840 } finally {
4841 Binder.restoreCallingIdentity(origId);
4842 }
4843 }
4844 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004845
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004846 @Override
4847 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004848 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004849 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004850 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004851 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004852 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004853 }
4854 }
4855
4856 @Override
4857 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004858 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004859 != PERMISSION_GRANTED) {
4860 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4861 + Binder.getCallingPid()
4862 + ", uid=" + Binder.getCallingUid()
4863 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4864 Slog.w(TAG, msg);
4865 throw new SecurityException(msg);
4866 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004867 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004868 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004869 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004870 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004871 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004872 }
4873 }
4874
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004875 @Override
4876 public void stopAppSwitches() {
4877 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4878 synchronized (mGlobalLock) {
4879 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004880 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004881 mDidAppSwitch = false;
4882 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4883 }
4884 }
4885
4886 @Override
4887 public void resumeAppSwitches() {
4888 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4889 synchronized (mGlobalLock) {
4890 // Note that we don't execute any pending app switches... we will
4891 // let those wait until either the timeout, or the next start
4892 // activity request.
4893 mAppSwitchesAllowedTime = 0;
4894 }
4895 }
4896
Ricky Wai906af482019-06-03 17:25:28 +01004897 long getLastStopAppSwitchesTime() {
4898 return mLastStopAppSwitchesTime;
4899 }
4900
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004901 void onStartActivitySetDidAppSwitch() {
4902 if (mDidAppSwitch) {
4903 // This is the second allowed switch since we stopped switches, so now just generally
4904 // allow switches. Use case:
4905 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4906 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4907 // anyone to switch again).
4908 mAppSwitchesAllowedTime = 0;
4909 } else {
4910 mDidAppSwitch = true;
4911 }
4912 }
4913
4914 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004915 boolean shouldDisableNonVrUiLocked() {
4916 return mVrController.shouldDisableNonVrUiLocked();
4917 }
4918
Wale Ogunwale53783742018-09-16 10:21:51 -07004919 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004920 // 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 +00004921 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004922 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004923 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4924 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004925 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004926 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004927 }
4928 mH.post(() -> {
4929 if (!mVrController.onVrModeChanged(r)) {
4930 return;
4931 }
4932 synchronized (mGlobalLock) {
4933 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4934 mWindowManager.disableNonVrUi(disableNonVrUi);
4935 if (disableNonVrUi) {
4936 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4937 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004938 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004939 }
4940 }
4941 });
4942 }
4943
Wale Ogunwale53783742018-09-16 10:21:51 -07004944 @Override
4945 public int getPackageScreenCompatMode(String packageName) {
4946 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4947 synchronized (mGlobalLock) {
4948 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4949 }
4950 }
4951
4952 @Override
4953 public void setPackageScreenCompatMode(String packageName, int mode) {
4954 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4955 "setPackageScreenCompatMode");
4956 synchronized (mGlobalLock) {
4957 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4958 }
4959 }
4960
4961 @Override
4962 public boolean getPackageAskScreenCompat(String packageName) {
4963 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4964 synchronized (mGlobalLock) {
4965 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4966 }
4967 }
4968
4969 @Override
4970 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4971 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4972 "setPackageAskScreenCompat");
4973 synchronized (mGlobalLock) {
4974 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4975 }
4976 }
4977
Wale Ogunwale64258362018-10-16 15:13:37 -07004978 public static String relaunchReasonToString(int relaunchReason) {
4979 switch (relaunchReason) {
4980 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4981 return "window_resize";
4982 case RELAUNCH_REASON_FREE_RESIZE:
4983 return "free_resize";
4984 default:
4985 return null;
4986 }
4987 }
4988
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004989 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004990 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004991 }
4992
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004993 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004994 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004995 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4996 }
4997
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004998 boolean isKeyguardLocked() {
4999 return mKeyguardController.isKeyguardLocked();
5000 }
5001
Garfield Tan01548632018-11-27 10:15:48 -08005002 /**
5003 * Clears launch params for the given package.
5004 * @param packageNames the names of the packages of which the launch params are to be cleared
5005 */
5006 @Override
5007 public void clearLaunchParamsForPackages(List<String> packageNames) {
5008 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5009 "clearLaunchParamsForPackages");
5010 synchronized (mGlobalLock) {
5011 for (int i = 0; i < packageNames.size(); ++i) {
5012 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
5013 }
5014 }
5015 }
5016
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005017 /**
5018 * Makes the display with the given id a single task instance display. I.e the display can only
5019 * contain one task.
5020 */
5021 @Override
5022 public void setDisplayToSingleTaskInstance(int displayId) {
5023 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5024 "setDisplayToSingleTaskInstance");
5025 final long origId = Binder.clearCallingIdentity();
5026 try {
Louis Chang677921f2019-12-06 16:44:24 +08005027 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08005028 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08005029 if (display != null) {
5030 display.setDisplayToSingleTaskInstance();
5031 }
5032 } finally {
5033 Binder.restoreCallingIdentity(origId);
5034 }
5035 }
5036
jorgegil@google.com06bc3232019-10-31 14:51:22 -07005037 /**
5038 * Requests that an activity should enter picture-in-picture mode if possible.
5039 */
5040 @Override
5041 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
5042 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
5043 "requestPictureInPictureMode");
5044 final long origId = Binder.clearCallingIdentity();
5045 try {
5046 synchronized (mGlobalLock) {
5047 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
5048 if (activity == null) {
5049 return;
5050 }
5051
5052 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
5053 "requestPictureInPictureMode", /* beforeStopping */ false);
5054 if (!canEnterPictureInPicture) {
5055 throw new IllegalStateException(
5056 "Requested PIP on an activity that doesn't support it");
5057 }
5058
5059 try {
5060 final ClientTransaction transaction = ClientTransaction.obtain(
5061 activity.app.getThread(),
5062 activity.token);
5063 transaction.addCallback(EnterPipRequestedItem.obtain());
5064 getLifecycleManager().scheduleTransaction(transaction);
5065 } catch (Exception e) {
5066 Slog.w(TAG, "Failed to send enter pip requested item: "
5067 + activity.intent.getComponent(), e);
5068 }
5069 }
5070 } finally {
5071 Binder.restoreCallingIdentity(origId);
5072 }
5073 }
5074
Wale Ogunwale31913b52018-10-13 08:29:31 -07005075 void dumpLastANRLocked(PrintWriter pw) {
5076 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5077 if (mLastANRState == null) {
5078 pw.println(" <no ANR has occurred since boot>");
5079 } else {
5080 pw.println(mLastANRState);
5081 }
5082 }
5083
5084 void dumpLastANRTracesLocked(PrintWriter pw) {
5085 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5086
5087 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5088 if (ArrayUtils.isEmpty(files)) {
5089 pw.println(" <no ANR has occurred since boot>");
5090 return;
5091 }
5092 // Find the latest file.
5093 File latest = null;
5094 for (File f : files) {
5095 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5096 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005097 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005098 }
5099 pw.print("File: ");
5100 pw.print(latest.getName());
5101 pw.println();
5102 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5103 String line;
5104 while ((line = in.readLine()) != null) {
5105 pw.println(line);
5106 }
5107 } catch (IOException e) {
5108 pw.print("Unable to read: ");
5109 pw.print(e);
5110 pw.println();
5111 }
5112 }
5113
5114 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5115 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5116 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5117 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5118 }
5119
5120 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5121 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5122 pw.println(header);
5123
Louis Chang149d5c82019-12-30 09:47:39 +08005124 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005125 dumpPackage);
5126 boolean needSep = printedAnything;
5127
5128 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005129 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005130 " ResumedActivity: ");
5131 if (printed) {
5132 printedAnything = true;
5133 needSep = false;
5134 }
5135
5136 if (dumpPackage == null) {
5137 if (needSep) {
5138 pw.println();
5139 }
5140 printedAnything = true;
5141 mStackSupervisor.dump(pw, " ");
5142 }
5143
5144 if (!printedAnything) {
5145 pw.println(" (nothing)");
5146 }
5147 }
5148
5149 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005150 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005151 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005152 pw.println(" ");
5153 }
5154
5155 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5156 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5157 getActivityStartController().dump(pw, "", dumpPackage);
5158 }
5159
5160 /**
5161 * There are three things that cmd can be:
5162 * - a flattened component name that matches an existing activity
5163 * - the cmd arg isn't the flattened component name of an existing activity:
5164 * dump all activity whose component contains the cmd as a substring
5165 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005166 * <p>
5167 * The caller should not hold lock when calling this method because it will wait for the
5168 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005169 *
5170 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5171 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5172 */
5173 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5174 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5175 ArrayList<ActivityRecord> activities;
5176
5177 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005178 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005179 dumpFocusedStackOnly);
5180 }
5181
5182 if (activities.size() <= 0) {
5183 return false;
5184 }
5185
5186 String[] newArgs = new String[args.length - opti];
5187 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5188
Louis Changcdec0802019-11-11 11:45:07 +08005189 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005190 boolean needSep = false;
5191 for (int i = activities.size() - 1; i >= 0; i--) {
5192 ActivityRecord r = activities.get(i);
5193 if (needSep) {
5194 pw.println();
5195 }
5196 needSep = true;
5197 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005198 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005199 if (lastTask != task) {
5200 lastTask = task;
5201 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005202 pw.print(" id="); pw.print(lastTask.mTaskId);
5203 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005204 if (dumpAll) {
5205 lastTask.dump(pw, " ");
5206 }
5207 }
5208 }
5209 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5210 }
5211 return true;
5212 }
5213
5214 /**
5215 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5216 * there is a thread associated with the activity.
5217 */
5218 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5219 final ActivityRecord r, String[] args, boolean dumpAll) {
5220 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005221 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005222 synchronized (mGlobalLock) {
5223 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5224 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5225 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005226 if (r.hasProcess()) {
5227 pw.println(r.app.getPid());
5228 appThread = r.app.getThread();
5229 } else {
5230 pw.println("(not running)");
5231 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005232 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005233 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005234 }
5235 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005236 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005237 // flush anything that is already in the PrintWriter since the thread is going
5238 // to write to the file descriptor directly
5239 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005240 try (TransferPipe tp = new TransferPipe()) {
5241 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5242 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005243 } catch (IOException e) {
5244 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5245 } catch (RemoteException e) {
5246 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5247 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005248 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005249 }
5250
sanryhuang498e77e2018-12-06 14:57:01 +08005251 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5252 boolean testPssMode) {
5253 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5254 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5255 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005256 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5258 st.toString());
5259 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005260 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5261 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5262 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005263 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5264 testPssMode);
5265 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005266 }
5267
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268 int getCurrentUserId() {
5269 return mAmInternal.getCurrentUserId();
5270 }
5271
5272 private void enforceNotIsolatedCaller(String caller) {
5273 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5274 throw new SecurityException("Isolated process not allowed to call " + caller);
5275 }
5276 }
5277
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 public Configuration getConfiguration() {
5279 Configuration ci;
5280 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005281 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005282 ci.userSetLocale = false;
5283 }
5284 return ci;
5285 }
5286
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287 /**
5288 * Current global configuration information. Contains general settings for the entire system,
5289 * also corresponds to the merged configuration of the default display.
5290 */
5291 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005292 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005293 // while initializing process record for system, see {@link
5294 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005295 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005296 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005297 }
5298
5299 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5300 boolean initLocale) {
5301 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5302 }
5303
5304 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5305 boolean initLocale, boolean deferResume) {
5306 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5307 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5308 UserHandle.USER_NULL, deferResume);
5309 }
5310
Wale Ogunwale59507092018-10-29 09:00:30 -07005311 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005312 final long origId = Binder.clearCallingIdentity();
5313 try {
5314 synchronized (mGlobalLock) {
5315 updateConfigurationLocked(values, null, false, true, userId,
5316 false /* deferResume */);
5317 }
5318 } finally {
5319 Binder.restoreCallingIdentity(origId);
5320 }
5321 }
5322
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005323 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5324 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5325 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5326 deferResume, null /* result */);
5327 }
5328
5329 /**
5330 * Do either or both things: (1) change the current configuration, and (2)
5331 * make sure the given activity is running with the (now) current
5332 * configuration. Returns true if the activity has been left running, or
5333 * false if <var>starting</var> is being destroyed to match the new
5334 * configuration.
5335 *
5336 * @param userId is only used when persistent parameter is set to true to persist configuration
5337 * for that particular user
5338 */
5339 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5340 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5341 ActivityTaskManagerService.UpdateConfigurationResult result) {
5342 int changes = 0;
5343 boolean kept = true;
5344
Riddle Hsua0022cd2019-09-09 21:12:41 +08005345 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005346 try {
5347 if (values != null) {
5348 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5349 deferResume);
5350 }
5351
5352 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5353 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005354 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005355 }
5356
5357 if (result != null) {
5358 result.changes = changes;
5359 result.activityRelaunched = !kept;
5360 }
5361 return kept;
5362 }
5363
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005364 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005365 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005366 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005367
Louis Chang677921f2019-12-06 16:44:24 +08005368 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005369 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005370
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005371 mTempConfig.setTo(getGlobalConfiguration());
5372 final int changes = mTempConfig.updateFrom(values);
5373 if (changes == 0) {
5374 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5375 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5376 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5377 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005378 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005379 return 0;
5380 }
5381
5382 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5383 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005384 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005385 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5386 values.colorMode,
5387 values.densityDpi,
5388 values.fontScale,
5389 values.hardKeyboardHidden,
5390 values.keyboard,
5391 values.keyboardHidden,
5392 values.mcc,
5393 values.mnc,
5394 values.navigation,
5395 values.navigationHidden,
5396 values.orientation,
5397 values.screenHeightDp,
5398 values.screenLayout,
5399 values.screenWidthDp,
5400 values.smallestScreenWidthDp,
5401 values.touchscreen,
5402 values.uiMode);
5403
5404
5405 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5406 final LocaleList locales = values.getLocales();
5407 int bestLocaleIndex = 0;
5408 if (locales.size() > 1) {
5409 if (mSupportedSystemLocales == null) {
5410 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5411 }
5412 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5413 }
5414 SystemProperties.set("persist.sys.locale",
5415 locales.get(bestLocaleIndex).toLanguageTag());
5416 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005417
5418 final Message m = PooledLambda.obtainMessage(
5419 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5420 locales.get(bestLocaleIndex));
5421 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005422 }
5423
Yunfan Chen75157d72018-07-27 14:47:21 +09005424 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005425
5426 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005427 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005428
5429 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5430 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005431 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005432
5433 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005434 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005435
5436 AttributeCache ac = AttributeCache.instance();
5437 if (ac != null) {
5438 ac.updateConfiguration(mTempConfig);
5439 }
5440
5441 // Make sure all resources in our process are updated right now, so that anyone who is going
5442 // to retrieve resource values after we return will be sure to get the new ones. This is
5443 // especially important during boot, where the first config change needs to guarantee all
5444 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005445 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005446
5447 // We need another copy of global config because we're scheduling some calls instead of
5448 // running them in place. We need to be sure that object we send will be handled unchanged.
5449 final Configuration configCopy = new Configuration(mTempConfig);
5450 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005451 final Message msg = PooledLambda.obtainMessage(
5452 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5453 this, userId, configCopy);
5454 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005455 }
5456
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005457 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5458 for (int i = pidMap.size() - 1; i >= 0; i--) {
5459 final int pid = pidMap.keyAt(i);
5460 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005461 if (DEBUG_CONFIGURATION) {
5462 Slog.v(TAG_CONFIGURATION, "Update process config of "
5463 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005464 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005465 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005466 }
5467
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005468 final Message msg = PooledLambda.obtainMessage(
5469 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5470 mAmInternal, changes, initLocale);
5471 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005472
5473 // Override configuration of the default display duplicates global config, so we need to
5474 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005475 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005476 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005477
5478 return changes;
5479 }
5480
Riddle Hsua0022cd2019-09-09 21:12:41 +08005481 /** @see WindowSurfacePlacer#deferLayout */
5482 void deferWindowLayout() {
5483 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5484 // Reset the reasons at the first entrance because we only care about the changes in the
5485 // deferred scope.
5486 mLayoutReasons = 0;
5487 }
5488
5489 mWindowManager.mWindowPlacerLocked.deferLayout();
5490 }
5491
5492 /** @see WindowSurfacePlacer#continueLayout */
5493 void continueWindowLayout() {
5494 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5495 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5496 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5497 }
5498 }
5499
5500 /**
5501 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5502 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5503 * defer count is gone.
5504 */
5505 void addWindowLayoutReasons(@LayoutReason int reasons) {
5506 mLayoutReasons |= reasons;
5507 }
5508
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 private void updateEventDispatchingLocked(boolean booted) {
5510 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5511 }
5512
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005513 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5514 final ContentResolver resolver = mContext.getContentResolver();
5515 Settings.System.putConfigurationForUser(resolver, config, userId);
5516 }
5517
5518 private void sendLocaleToMountDaemonMsg(Locale l) {
5519 try {
5520 IBinder service = ServiceManager.getService("mount");
5521 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5522 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5523 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5524 } catch (RemoteException e) {
5525 Log.e(TAG, "Error storing locale for decryption UI", e);
5526 }
5527 }
5528
Alison Cichowlas3e340502018-08-07 17:15:01 -04005529 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5530 mStartActivitySources.remove(permissionToken);
5531 mExpiredStartAsCallerTokens.add(permissionToken);
5532 }
5533
5534 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5535 mExpiredStartAsCallerTokens.remove(permissionToken);
5536 }
5537
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005538 boolean isActivityStartsLoggingEnabled() {
5539 return mAmInternal.isActivityStartsLoggingEnabled();
5540 }
5541
Michal Karpinski8596ded2018-11-14 14:43:48 +00005542 boolean isBackgroundActivityStartsEnabled() {
5543 return mAmInternal.isBackgroundActivityStartsEnabled();
5544 }
5545
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005547 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 mWindowManager.enableScreenAfterBoot();
5549
5550 synchronized (mGlobalLock) {
5551 updateEventDispatchingLocked(booted);
5552 }
5553 }
5554
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005555 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5556 if (r == null || !r.hasProcess()) {
5557 return KEY_DISPATCHING_TIMEOUT_MS;
5558 }
5559 return getInputDispatchingTimeoutLocked(r.app);
5560 }
5561
5562 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005563 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005564 }
5565
Wale Ogunwalef6733932018-06-27 05:14:34 -07005566 /**
5567 * Decide based on the configuration whether we should show the ANR,
5568 * crash, etc dialogs. The idea is that if there is no affordance to
5569 * press the on-screen buttons, or the user experience would be more
5570 * greatly impacted than the crash itself, we shouldn't show the dialog.
5571 *
5572 * A thought: SystemUI might also want to get told about this, the Power
5573 * dialog / global actions also might want different behaviors.
5574 */
5575 private void updateShouldShowDialogsLocked(Configuration config) {
5576 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5577 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5578 && config.navigation == Configuration.NAVIGATION_NONAV);
5579 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5580 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5581 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5582 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5583 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5584 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5585 HIDE_ERROR_DIALOGS, 0) != 0;
5586 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5587 }
5588
5589 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5590 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5591 FONT_SCALE, 1.0f, userId);
5592
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005593 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005594 if (getGlobalConfiguration().fontScale == scaleFactor) {
5595 return;
5596 }
5597
5598 final Configuration configuration
5599 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5600 configuration.fontScale = scaleFactor;
5601 updatePersistentConfiguration(configuration, userId);
5602 }
5603 }
5604
5605 // Actually is sleeping or shutting down or whatever else in the future
5606 // is an inactive state.
5607 boolean isSleepingOrShuttingDownLocked() {
5608 return isSleepingLocked() || mShuttingDown;
5609 }
5610
5611 boolean isSleepingLocked() {
5612 return mSleeping;
5613 }
5614
Riddle Hsu16567132018-08-16 21:37:47 +08005615 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005616 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005617 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005618 if (task.isActivityTypeStandard()) {
5619 if (mCurAppTimeTracker != r.appTimeTracker) {
5620 // We are switching app tracking. Complete the current one.
5621 if (mCurAppTimeTracker != null) {
5622 mCurAppTimeTracker.stop();
5623 mH.obtainMessage(
5624 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005625 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005626 mCurAppTimeTracker = null;
5627 }
5628 if (r.appTimeTracker != null) {
5629 mCurAppTimeTracker = r.appTimeTracker;
5630 startTimeTrackingFocusedActivityLocked();
5631 }
5632 } else {
5633 startTimeTrackingFocusedActivityLocked();
5634 }
5635 } else {
5636 r.appTimeTracker = null;
5637 }
5638 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5639 // TODO: Probably not, because we don't want to resume voice on switching
5640 // back to this activity
5641 if (task.voiceInteractor != null) {
5642 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5643 } else {
5644 finishRunningVoiceLocked();
5645
5646 if (mLastResumedActivity != null) {
5647 final IVoiceInteractionSession session;
5648
Louis Changcdec0802019-11-11 11:45:07 +08005649 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005650 if (lastResumedActivityTask != null
5651 && lastResumedActivityTask.voiceSession != null) {
5652 session = lastResumedActivityTask.voiceSession;
5653 } else {
5654 session = mLastResumedActivity.voiceSession;
5655 }
5656
5657 if (session != null) {
5658 // We had been in a voice interaction session, but now focused has
5659 // move to something different. Just finish the session, we can't
5660 // return to it and retain the proper state and synchronization with
5661 // the voice interaction service.
5662 finishVoiceTask(session);
5663 }
5664 }
5665 }
5666
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005667 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5668 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005669 }
5670 updateResumedAppTrace(r);
5671 mLastResumedActivity = r;
5672
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005673 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005674
5675 applyUpdateLockStateLocked(r);
5676 applyUpdateVrModeLocked(r);
5677
Jeff Changd136e772019-11-05 20:33:52 +08005678 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005679 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005680 r == null ? "NULL" : r.shortComponentName,
5681 reason);
5682 }
5683
5684 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5685 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005686 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005687 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005688 updateSleepIfNeededLocked();
5689 return token;
5690 }
5691 }
5692
5693 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005694 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005695 final boolean wasSleeping = mSleeping;
5696 boolean updateOomAdj = false;
5697
5698 if (!shouldSleep) {
5699 // If wasSleeping is true, we need to wake up activity manager state from when
5700 // we started sleeping. In either case, we need to apply the sleep tokens, which
5701 // will wake up stacks or put them to sleep as appropriate.
5702 if (wasSleeping) {
5703 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005704 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5705 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005706 startTimeTrackingFocusedActivityLocked();
5707 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005708 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005709 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5710 }
Louis Chang149d5c82019-12-30 09:47:39 +08005711 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005712 if (wasSleeping) {
5713 updateOomAdj = true;
5714 }
5715 } else if (!mSleeping && shouldSleep) {
5716 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005717 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5718 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005719 if (mCurAppTimeTracker != null) {
5720 mCurAppTimeTracker.stop();
5721 }
5722 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005723 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005724 mStackSupervisor.goingToSleepLocked();
5725 updateResumedAppTrace(null /* resumed */);
5726 updateOomAdj = true;
5727 }
5728 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005729 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005730 }
5731 }
5732
5733 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005734 mH.removeCallbacks(mUpdateOomAdjRunnable);
5735 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005736 }
5737
Wale Ogunwale53783742018-09-16 10:21:51 -07005738 void updateCpuStats() {
5739 mH.post(mAmInternal::updateCpuStats);
5740 }
5741
Hui Yu03d12402018-12-06 18:00:37 -08005742 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5743 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005744 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5745 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005746 mH.sendMessage(m);
5747 }
5748
Hui Yu03d12402018-12-06 18:00:37 -08005749 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005750 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005751 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005752 if (task != null) {
5753 final ActivityRecord rootActivity = task.getRootActivity();
5754 if (rootActivity != null) {
5755 taskRoot = rootActivity.mActivityComponent;
5756 }
5757 }
5758
Hui Yu03d12402018-12-06 18:00:37 -08005759 final Message m = PooledLambda.obtainMessage(
5760 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005761 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005762 mH.sendMessage(m);
5763 }
5764
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005765 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5766 String hostingType) {
5767 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005768 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5769 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005770 + activity.processName);
5771 }
5772 // Post message to start process to avoid possible deadlock of calling into AMS with the
5773 // ATMS lock held.
5774 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5775 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5776 isTop, hostingType, activity.intent.getComponent());
5777 mH.sendMessage(m);
5778 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005779 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005780 }
5781 }
5782
Wale Ogunwale53783742018-09-16 10:21:51 -07005783 void setBooting(boolean booting) {
5784 mAmInternal.setBooting(booting);
5785 }
5786
5787 boolean isBooting() {
5788 return mAmInternal.isBooting();
5789 }
5790
5791 void setBooted(boolean booted) {
5792 mAmInternal.setBooted(booted);
5793 }
5794
5795 boolean isBooted() {
5796 return mAmInternal.isBooted();
5797 }
5798
5799 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5800 mH.post(() -> {
5801 if (finishBooting) {
5802 mAmInternal.finishBooting();
5803 }
5804 if (enableScreen) {
5805 mInternal.enableScreenAfterBoot(isBooted());
5806 }
5807 });
5808 }
5809
5810 void setHeavyWeightProcess(ActivityRecord root) {
5811 mHeavyWeightProcess = root.app;
5812 final Message m = PooledLambda.obtainMessage(
5813 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005814 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005815 mH.sendMessage(m);
5816 }
5817
5818 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5819 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5820 return;
5821 }
5822
5823 mHeavyWeightProcess = null;
5824 final Message m = PooledLambda.obtainMessage(
5825 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5826 proc.mUserId);
5827 mH.sendMessage(m);
5828 }
5829
5830 private void cancelHeavyWeightProcessNotification(int userId) {
5831 final INotificationManager inm = NotificationManager.getService();
5832 if (inm == null) {
5833 return;
5834 }
5835 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005836 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005837 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5838 } catch (RuntimeException e) {
5839 Slog.w(TAG, "Error canceling notification for service", e);
5840 } catch (RemoteException e) {
5841 }
5842
5843 }
5844
5845 private void postHeavyWeightProcessNotification(
5846 WindowProcessController proc, Intent intent, int userId) {
5847 if (proc == null) {
5848 return;
5849 }
5850
5851 final INotificationManager inm = NotificationManager.getService();
5852 if (inm == null) {
5853 return;
5854 }
5855
5856 try {
5857 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5858 String text = mContext.getString(R.string.heavy_weight_notification,
5859 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5860 Notification notification =
5861 new Notification.Builder(context,
5862 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5863 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5864 .setWhen(0)
5865 .setOngoing(true)
5866 .setTicker(text)
5867 .setColor(mContext.getColor(
5868 com.android.internal.R.color.system_notification_accent_color))
5869 .setContentTitle(text)
5870 .setContentText(
5871 mContext.getText(R.string.heavy_weight_notification_detail))
5872 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5873 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5874 new UserHandle(userId)))
5875 .build();
5876 try {
5877 inm.enqueueNotificationWithTag("android", "android", null,
5878 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5879 } catch (RuntimeException e) {
5880 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5881 } catch (RemoteException e) {
5882 }
5883 } catch (PackageManager.NameNotFoundException e) {
5884 Slog.w(TAG, "Unable to create context for heavy notification", e);
5885 }
5886
5887 }
5888
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005889 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5890 IBinder token, String resultWho, int requestCode, Intent[] intents,
5891 String[] resolvedTypes, int flags, Bundle bOptions) {
5892
5893 ActivityRecord activity = null;
5894 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5895 activity = ActivityRecord.isInStackLocked(token);
5896 if (activity == null) {
5897 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5898 return null;
5899 }
5900 if (activity.finishing) {
5901 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5902 return null;
5903 }
5904 }
5905
5906 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5907 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5908 bOptions);
5909 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5910 if (noCreate) {
5911 return rec;
5912 }
5913 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5914 if (activity.pendingResults == null) {
5915 activity.pendingResults = new HashSet<>();
5916 }
5917 activity.pendingResults.add(rec.ref);
5918 }
5919 return rec;
5920 }
5921
Andrii Kulian52d255c2018-07-13 11:32:19 -07005922 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005923 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005924 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005925 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5926 mCurAppTimeTracker.start(resumedActivity.packageName);
5927 }
5928 }
5929
5930 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5931 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005932 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005933 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5934 }
5935 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005936 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005937 constructResumedTraceName(resumed.packageName), 0);
5938 }
5939 mTracedResumedActivity = resumed;
5940 }
5941
5942 private String constructResumedTraceName(String packageName) {
5943 return "focused app: " + packageName;
5944 }
5945
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005946 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005947 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005948 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005949 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005950 // mainStack is null during startup.
5951 if (mainStack != null) {
5952 if (changes != 0 && starting == null) {
5953 // If the configuration changed, and the caller is not already
5954 // in the process of starting an activity, then find the top
5955 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005956 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005957 }
5958
5959 if (starting != null) {
5960 kept = starting.ensureActivityConfiguration(changes,
5961 false /* preserveWindow */);
5962 // And we need to make sure at this point that all other activities
5963 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005964 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005965 !PRESERVE_WINDOWS);
5966 }
5967 }
5968
5969 return kept;
5970 }
5971
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005972 void scheduleAppGcsLocked() {
5973 mH.post(() -> mAmInternal.scheduleAppGcs());
5974 }
5975
Wale Ogunwale53783742018-09-16 10:21:51 -07005976 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5977 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5978 }
5979
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005980 /**
5981 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5982 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5983 * on demand.
5984 */
5985 IPackageManager getPackageManager() {
5986 return AppGlobals.getPackageManager();
5987 }
5988
5989 PackageManagerInternal getPackageManagerInternalLocked() {
5990 if (mPmInternal == null) {
5991 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5992 }
5993 return mPmInternal;
5994 }
5995
Hai Zhangf4da9be2019-05-01 13:46:06 +08005996 PermissionPolicyInternal getPermissionPolicyInternal() {
5997 if (mPermissionPolicyInternal == null) {
5998 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5999 }
6000 return mPermissionPolicyInternal;
6001 }
6002
Wale Ogunwale008163e2018-07-23 23:11:08 -07006003 AppWarnings getAppWarningsLocked() {
6004 return mAppWarnings;
6005 }
6006
Wale Ogunwale214f3482018-10-04 11:00:47 -07006007 Intent getHomeIntent() {
6008 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
6009 intent.setComponent(mTopComponent);
6010 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6011 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6012 intent.addCategory(Intent.CATEGORY_HOME);
6013 }
6014 return intent;
6015 }
6016
Chilun2ef71f72018-11-16 17:57:15 +08006017 /**
6018 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
6019 * activities.
6020 *
6021 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
6022 * component defined in config_secondaryHomeComponent.
6023 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
6024 */
6025 Intent getSecondaryHomeIntent(String preferredPackage) {
6026 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07006027 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
6028 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
6029 if (preferredPackage == null || useSystemProvidedLauncher) {
6030 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08006031 final String secondaryHomeComponent = mContext.getResources().getString(
6032 com.android.internal.R.string.config_secondaryHomeComponent);
6033 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
6034 } else {
6035 intent.setPackage(preferredPackage);
6036 }
6037 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
6038 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
6039 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
6040 }
6041 return intent;
6042 }
6043
Wale Ogunwale214f3482018-10-04 11:00:47 -07006044 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
6045 if (info == null) return null;
6046 ApplicationInfo newInfo = new ApplicationInfo(info);
6047 newInfo.initForUser(userId);
6048 return newInfo;
6049 }
6050
Wale Ogunwale9c103022018-10-18 07:44:54 -07006051 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006052 if (uid == SYSTEM_UID) {
6053 // The system gets to run in any process. If there are multiple processes with the same
6054 // uid, just pick the first (this should never happen).
6055 final SparseArray<WindowProcessController> procs =
6056 mProcessNames.getMap().get(processName);
6057 if (procs == null) return null;
6058 final int procCount = procs.size();
6059 for (int i = 0; i < procCount; i++) {
6060 final int procUid = procs.keyAt(i);
6061 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
6062 // Don't use an app process or different user process for system component.
6063 continue;
6064 }
6065 return procs.valueAt(i);
6066 }
6067 }
6068
6069 return mProcessNames.get(processName, uid);
6070 }
6071
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006072 WindowProcessController getProcessController(IApplicationThread thread) {
6073 if (thread == null) {
6074 return null;
6075 }
6076
6077 final IBinder threadBinder = thread.asBinder();
6078 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6079 for (int i = pmap.size()-1; i >= 0; i--) {
6080 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6081 for (int j = procs.size() - 1; j >= 0; j--) {
6082 final WindowProcessController proc = procs.valueAt(j);
6083 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6084 return proc;
6085 }
6086 }
6087 }
6088
6089 return null;
6090 }
6091
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006092 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006093 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006094 if (proc == null) return null;
6095 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6096 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006097 }
6098 return null;
6099 }
6100
Riddle Hsua0536432019-02-16 00:38:59 +08006101 int getUidState(int uid) {
6102 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006103 }
6104
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006105 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006106 // A uid is considered to be foreground if it has a visible non-toast window.
6107 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006108 }
6109
Ricky Wai96f5c352019-04-10 18:40:17 +01006110 boolean isDeviceOwner(int uid) {
6111 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006112 }
6113
Ricky Wai96f5c352019-04-10 18:40:17 +01006114 void setDeviceOwnerUid(int uid) {
6115 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006116 }
6117
Wale Ogunwale9de19442018-10-18 19:05:03 -07006118 /**
6119 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6120 * the whitelist
6121 */
6122 String getPendingTempWhitelistTagForUidLocked(int uid) {
6123 return mPendingTempWhitelist.get(uid);
6124 }
6125
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006126 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6127 if (true || Build.IS_USER) {
6128 return;
6129 }
6130
6131 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6132 StrictMode.allowThreadDiskWrites();
6133 try {
6134 File tracesDir = new File("/data/anr");
6135 File tracesFile = null;
6136 try {
6137 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6138
6139 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006140 String timeString =
6141 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6142 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006143 sb.append(": ");
6144 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6145 sb.append(" since ");
6146 sb.append(msg);
6147 FileOutputStream fos = new FileOutputStream(tracesFile);
6148 fos.write(sb.toString().getBytes());
6149 if (app == null) {
6150 fos.write("\n*** No application process!".getBytes());
6151 }
6152 fos.close();
6153 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6154 } catch (IOException e) {
6155 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6156 return;
6157 }
6158
6159 if (app != null && app.getPid() > 0) {
6160 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6161 firstPids.add(app.getPid());
6162 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6163 }
6164
6165 File lastTracesFile = null;
6166 File curTracesFile = null;
6167 for (int i=9; i>=0; i--) {
6168 String name = String.format(Locale.US, "slow%02d.txt", i);
6169 curTracesFile = new File(tracesDir, name);
6170 if (curTracesFile.exists()) {
6171 if (lastTracesFile != null) {
6172 curTracesFile.renameTo(lastTracesFile);
6173 } else {
6174 curTracesFile.delete();
6175 }
6176 }
6177 lastTracesFile = curTracesFile;
6178 }
6179 tracesFile.renameTo(curTracesFile);
6180 } finally {
6181 StrictMode.setThreadPolicy(oldPolicy);
6182 }
6183 }
6184
Michal Karpinskida34cd42019-04-02 19:46:52 +01006185 boolean isAssociatedCompanionApp(int userId, int uid) {
6186 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6187 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006188 return false;
6189 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006190 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006191 }
6192
Issei Suzuki734bc942019-06-05 13:59:52 +02006193 void notifySingleTaskDisplayEmpty(int displayId) {
6194 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6195 }
6196
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006197 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006198 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006199
6200
Wale Ogunwale98875612018-10-12 07:53:02 -07006201 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6202 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006203
Riddle Hsud93a6c42018-11-29 21:50:06 +08006204 H(Looper looper) {
6205 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006206 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006207
6208 @Override
6209 public void handleMessage(Message msg) {
6210 switch (msg.what) {
6211 case REPORT_TIME_TRACKER_MSG: {
6212 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6213 tracker.deliverResult(mContext);
6214 } break;
6215 }
6216 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006217 }
6218
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006219 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006220 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006221
6222 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006223 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006224 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006225
6226 @Override
6227 public void handleMessage(Message msg) {
6228 switch (msg.what) {
6229 case DISMISS_DIALOG_UI_MSG: {
6230 final Dialog d = (Dialog) msg.obj;
6231 d.dismiss();
6232 break;
6233 }
6234 }
6235 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006236 }
6237
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006238 final class LocalService extends ActivityTaskManagerInternal {
6239 @Override
6240 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006241 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006242 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006243 }
6244
6245 @Override
6246 public ComponentName getHomeActivityForUser(int userId) {
6247 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006248 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006249 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006250 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006251 }
6252 }
6253
6254 @Override
6255 public void onLocalVoiceInteractionStarted(IBinder activity,
6256 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6257 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006258 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006259 }
6260 }
6261
6262 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006263 public void notifySingleTaskDisplayDrawn(int displayId) {
6264 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6265 }
6266
6267 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006268 public void notifyAppTransitionFinished() {
6269 synchronized (mGlobalLock) {
6270 mStackSupervisor.notifyAppTransitionDone();
6271 }
6272 }
6273
6274 @Override
6275 public void notifyAppTransitionCancelled() {
6276 synchronized (mGlobalLock) {
6277 mStackSupervisor.notifyAppTransitionDone();
6278 }
6279 }
6280
6281 @Override
6282 public List<IBinder> getTopVisibleActivities() {
6283 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006284 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006285 }
6286 }
6287
6288 @Override
6289 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6290 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006291 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006292 }
6293 }
6294
6295 @Override
6296 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6297 Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006298 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006299 final String[] resolvedTypes = new String[intents.length];
6300
6301 // UID of the package on user userId.
6302 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6303 // packageUid may not be initialized.
6304 int packageUid = 0;
6305 final long ident = Binder.clearCallingIdentity();
6306
6307 try {
6308 for (int i = 0; i < intents.length; i++) {
6309 resolvedTypes[i] =
6310 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6311 }
6312
6313 packageUid = AppGlobals.getPackageManager().getPackageUid(
6314 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6315 } catch (RemoteException e) {
6316 // Shouldn't happen.
6317 } finally {
6318 Binder.restoreCallingIdentity(ident);
6319 }
6320
Riddle Hsu591bf612019-02-14 17:55:31 +08006321 return getActivityStartController().startActivitiesInPackage(
6322 packageUid, packageName,
6323 intents, resolvedTypes, null /* resultTo */,
6324 SafeActivityOptions.fromBundle(bOptions), userId,
6325 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6326 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006327 }
6328
6329 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006330 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6331 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6332 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6333 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006334 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006335 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006336 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6337 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6338 userId, validateIncomingUser, originatingPendingIntent,
6339 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006340 }
6341 }
6342
6343 @Override
6344 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6345 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6346 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006347 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006348 PendingIntentRecord originatingPendingIntent,
6349 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006350 synchronized (mGlobalLock) {
6351 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6352 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6353 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006354 validateIncomingUser, originatingPendingIntent,
6355 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006356 }
6357 }
6358
6359 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006360 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6361 Intent intent, Bundle options, int userId) {
6362 return ActivityTaskManagerService.this.startActivityAsUser(
6363 caller, callerPacakge, intent,
6364 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6365 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6366 false /*validateIncomingUser*/);
6367 }
6368
6369 @Override
lumark588a3e82018-07-20 18:53:54 +08006370 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006371 synchronized (mGlobalLock) {
6372
6373 // We might change the visibilities here, so prepare an empty app transition which
6374 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006375 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006376 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006377 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006378 return;
6379 }
Louis Chang677921f2019-12-06 16:44:24 +08006380 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006381 final boolean wasTransitionSet =
6382 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006383 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006384 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006385 }
Louis Chang149d5c82019-12-30 09:47:39 +08006386 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006387
6388 // If there was a transition set already we don't want to interfere with it as we
6389 // might be starting it too early.
6390 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006391 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006392 }
6393 }
6394 if (callback != null) {
6395 callback.run();
6396 }
6397 }
6398
6399 @Override
6400 public void notifyKeyguardTrustedChanged() {
6401 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006402 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006403 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006404 }
6405 }
6406 }
6407
6408 /**
6409 * Called after virtual display Id is updated by
6410 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6411 * {@param vrVr2dDisplayId}.
6412 */
6413 @Override
6414 public void setVr2dDisplayId(int vr2dDisplayId) {
6415 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6416 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006417 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006418 }
6419 }
6420
6421 @Override
6422 public void setFocusedActivity(IBinder token) {
6423 synchronized (mGlobalLock) {
6424 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6425 if (r == null) {
6426 throw new IllegalArgumentException(
6427 "setFocusedActivity: No activity record matching token=" + token);
6428 }
Louis Chang19443452018-10-09 12:10:21 +08006429 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006430 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006431 }
6432 }
6433 }
6434
6435 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006436 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006437 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006438 }
6439
6440 @Override
6441 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006442 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006443 }
6444
6445 @Override
6446 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006447 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006448 }
6449
6450 @Override
6451 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6452 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6453 }
6454
6455 @Override
6456 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006457 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006458 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006459
6460 @Override
6461 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6462 synchronized (mGlobalLock) {
6463 mActiveVoiceInteractionServiceComponent = component;
6464 }
6465 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006466
6467 @Override
6468 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6469 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6470 return;
6471 }
6472 synchronized (mGlobalLock) {
6473 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6474 if (types == null) {
6475 if (uid < 0) {
6476 return;
6477 }
6478 types = new ArrayMap<>();
6479 mAllowAppSwitchUids.put(userId, types);
6480 }
6481 if (uid < 0) {
6482 types.remove(type);
6483 } else {
6484 types.put(type, uid);
6485 }
6486 }
6487 }
6488
6489 @Override
6490 public void onUserStopped(int userId) {
6491 synchronized (mGlobalLock) {
6492 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6493 mAllowAppSwitchUids.remove(userId);
6494 }
6495 }
6496
6497 @Override
6498 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6499 synchronized (mGlobalLock) {
6500 return ActivityTaskManagerService.this.isGetTasksAllowed(
6501 caller, callingPid, callingUid);
6502 }
6503 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006504
Riddle Hsua0536432019-02-16 00:38:59 +08006505 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006506 @Override
6507 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006508 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006509 mProcessNames.put(proc.mName, proc.mUid, proc);
6510 }
6511 }
6512
Riddle Hsua0536432019-02-16 00:38:59 +08006513 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006514 @Override
6515 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006516 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006517 mProcessNames.remove(name, uid);
6518 }
6519 }
6520
Riddle Hsua0536432019-02-16 00:38:59 +08006521 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006522 @Override
6523 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006524 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006525 if (proc == mHomeProcess) {
6526 mHomeProcess = null;
6527 }
6528 if (proc == mPreviousProcess) {
6529 mPreviousProcess = null;
6530 }
6531 }
6532 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006533
Riddle Hsua0536432019-02-16 00:38:59 +08006534 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006535 @Override
6536 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006537 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006538 return mTopProcessState;
6539 }
6540 }
6541
Riddle Hsua0536432019-02-16 00:38:59 +08006542 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006543 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006544 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006545 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006546 return proc == mHeavyWeightProcess;
6547 }
6548 }
6549
Riddle Hsua0536432019-02-16 00:38:59 +08006550 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006551 @Override
6552 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006553 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006554 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6555 }
6556 }
6557
6558 @Override
6559 public void finishHeavyWeightApp() {
6560 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006561 if (mHeavyWeightProcess != null) {
6562 mHeavyWeightProcess.finishActivities();
6563 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006564 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6565 mHeavyWeightProcess);
6566 }
6567 }
6568
Riddle Hsua0536432019-02-16 00:38:59 +08006569 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006570 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006571 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006572 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006573 return isSleepingLocked();
6574 }
6575 }
6576
6577 @Override
6578 public boolean isShuttingDown() {
6579 synchronized (mGlobalLock) {
6580 return mShuttingDown;
6581 }
6582 }
6583
6584 @Override
6585 public boolean shuttingDown(boolean booted, int timeout) {
6586 synchronized (mGlobalLock) {
6587 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006588 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006589 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006590 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006591 return mStackSupervisor.shutdownLocked(timeout);
6592 }
6593 }
6594
6595 @Override
6596 public void enableScreenAfterBoot(boolean booted) {
6597 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006598 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006599 mWindowManager.enableScreenAfterBoot();
6600 updateEventDispatchingLocked(booted);
6601 }
6602 }
6603
6604 @Override
6605 public boolean showStrictModeViolationDialog() {
6606 synchronized (mGlobalLock) {
6607 return mShowDialogs && !mSleeping && !mShuttingDown;
6608 }
6609 }
6610
6611 @Override
6612 public void showSystemReadyErrorDialogsIfNeeded() {
6613 synchronized (mGlobalLock) {
6614 try {
6615 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6616 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6617 + " data partition or your device will be unstable.");
6618 mUiHandler.post(() -> {
6619 if (mShowDialogs) {
6620 AlertDialog d = new BaseErrorDialog(mUiContext);
6621 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6622 d.setCancelable(false);
6623 d.setTitle(mUiContext.getText(R.string.android_system_label));
6624 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6625 d.setButton(DialogInterface.BUTTON_POSITIVE,
6626 mUiContext.getText(R.string.ok),
6627 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6628 d.show();
6629 }
6630 });
6631 }
6632 } catch (RemoteException e) {
6633 }
6634
6635 if (!Build.isBuildConsistent()) {
6636 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6637 mUiHandler.post(() -> {
6638 if (mShowDialogs) {
6639 AlertDialog d = new BaseErrorDialog(mUiContext);
6640 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6641 d.setCancelable(false);
6642 d.setTitle(mUiContext.getText(R.string.android_system_label));
6643 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6644 d.setButton(DialogInterface.BUTTON_POSITIVE,
6645 mUiContext.getText(R.string.ok),
6646 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6647 d.show();
6648 }
6649 });
6650 }
6651 }
6652 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006653
6654 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006655 public void onProcessMapped(int pid, WindowProcessController proc) {
6656 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006657 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006658 }
6659 }
6660
6661 @Override
6662 public void onProcessUnMapped(int pid) {
6663 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006664 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006665 }
6666 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006667
6668 @Override
6669 public void onPackageDataCleared(String name) {
6670 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006671 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006672 mAppWarnings.onPackageDataCleared(name);
6673 }
6674 }
6675
6676 @Override
6677 public void onPackageUninstalled(String name) {
6678 synchronized (mGlobalLock) {
6679 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006680 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006681 }
6682 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006683
6684 @Override
6685 public void onPackageAdded(String name, boolean replacing) {
6686 synchronized (mGlobalLock) {
6687 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6688 }
6689 }
6690
6691 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006692 public void onPackageReplaced(ApplicationInfo aInfo) {
6693 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006694 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 }
6696 }
6697
6698 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006699 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6700 synchronized (mGlobalLock) {
6701 return compatibilityInfoForPackageLocked(ai);
6702 }
6703 }
6704
Yunfan Chen75157d72018-07-27 14:47:21 +09006705 /**
6706 * Set the corresponding display information for the process global configuration. To be
6707 * called when we need to show IME on a different display.
6708 *
6709 * @param pid The process id associated with the IME window.
6710 * @param displayId The ID of the display showing the IME.
6711 */
6712 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006713 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006714 // Don't update process-level configuration for Multi-Client IME process since other
6715 // IMEs on other displays will also receive this configuration change due to IME
6716 // services use the same application config/context.
6717 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006718
Yunfan Chen75157d72018-07-27 14:47:21 +09006719 if (pid == MY_PID || pid < 0) {
6720 if (DEBUG_CONFIGURATION) {
6721 Slog.w(TAG,
6722 "Trying to update display configuration for system/invalid process.");
6723 }
6724 return;
6725 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006726 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006727 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006728 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006729 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006730 // Call might come when display is not yet added or has been removed.
6731 if (DEBUG_CONFIGURATION) {
6732 Slog.w(TAG, "Trying to update display configuration for non-existing "
6733 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006734 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006735 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006736 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006737 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006738 if (process == null) {
6739 if (DEBUG_CONFIGURATION) {
6740 Slog.w(TAG, "Trying to update display configuration for invalid "
6741 + "process, pid=" + pid);
6742 }
6743 return;
6744 }
lumarkddc77fb2019-06-27 22:22:23 +08006745 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006746 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006747 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006748 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006749
6750 @Override
6751 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006752 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006753 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006754 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6755 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006756 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006757 }
6758 }
6759 }
6760
6761 @Override
6762 public void clearPendingResultForActivity(IBinder activityToken,
6763 WeakReference<PendingIntentRecord> pir) {
6764 synchronized (mGlobalLock) {
6765 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6766 if (r != null && r.pendingResults != null) {
6767 r.pendingResults.remove(pir);
6768 }
6769 }
6770 }
6771
6772 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006773 public ActivityTokens getTopActivityForTask(int taskId) {
6774 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006775 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006776 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006777 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6778 + " Requested task not found");
6779 return null;
6780 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006781 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006782 if (activity == null) {
6783 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6784 + " Requested activity not found");
6785 return null;
6786 }
6787 if (!activity.attachedToProcess()) {
6788 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6789 + activity);
6790 return null;
6791 }
6792 return new ActivityTokens(activity.appToken, activity.assistToken,
6793 activity.app.getThread());
6794 }
6795 }
6796
6797 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006798 public IIntentSender getIntentSender(int type, String packageName,
6799 int callingUid, int userId, IBinder token, String resultWho,
6800 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6801 Bundle bOptions) {
6802 synchronized (mGlobalLock) {
6803 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6804 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6805 }
6806 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006807
6808 @Override
6809 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6810 synchronized (mGlobalLock) {
6811 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6812 if (r == null) {
6813 return null;
6814 }
6815 if (r.mServiceConnectionsHolder == null) {
6816 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6817 ActivityTaskManagerService.this, r);
6818 }
6819
6820 return r.mServiceConnectionsHolder;
6821 }
6822 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006823
6824 @Override
6825 public Intent getHomeIntent() {
6826 synchronized (mGlobalLock) {
6827 return ActivityTaskManagerService.this.getHomeIntent();
6828 }
6829 }
6830
6831 @Override
6832 public boolean startHomeActivity(int userId, String reason) {
6833 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006834 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006835 }
6836 }
6837
6838 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006839 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006840 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006841 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006842 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006843 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006844 }
Chilun8b1f1be2019-03-13 17:14:36 +08006845 }
6846
6847 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006848 public boolean startHomeOnAllDisplays(int userId, String reason) {
6849 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006850 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006851 }
6852 }
6853
Riddle Hsua0536432019-02-16 00:38:59 +08006854 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006855 @Override
6856 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006857 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006858 if (mFactoryTest == FACTORY_TEST_OFF) {
6859 return false;
6860 }
6861 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6862 && wpc.mName.equals(mTopComponent.getPackageName())) {
6863 return true;
6864 }
6865 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6866 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6867 }
6868 }
6869
6870 @Override
6871 public void updateTopComponentForFactoryTest() {
6872 synchronized (mGlobalLock) {
6873 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6874 return;
6875 }
6876 final ResolveInfo ri = mContext.getPackageManager()
6877 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6878 final CharSequence errorMsg;
6879 if (ri != null) {
6880 final ActivityInfo ai = ri.activityInfo;
6881 final ApplicationInfo app = ai.applicationInfo;
6882 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6883 mTopAction = Intent.ACTION_FACTORY_TEST;
6884 mTopData = null;
6885 mTopComponent = new ComponentName(app.packageName, ai.name);
6886 errorMsg = null;
6887 } else {
6888 errorMsg = mContext.getResources().getText(
6889 com.android.internal.R.string.factorytest_not_system);
6890 }
6891 } else {
6892 errorMsg = mContext.getResources().getText(
6893 com.android.internal.R.string.factorytest_no_action);
6894 }
6895 if (errorMsg == null) {
6896 return;
6897 }
6898
6899 mTopAction = null;
6900 mTopData = null;
6901 mTopComponent = null;
6902 mUiHandler.post(() -> {
6903 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6904 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006905 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006906 });
6907 }
6908 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909
Riddle Hsua0536432019-02-16 00:38:59 +08006910 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006911 @Override
6912 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6913 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006914 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006916 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006917
6918 wpc.clearRecentTasks();
6919 wpc.clearActivities();
6920
6921 if (wpc.isInstrumenting()) {
6922 finishInstrumentationCallback.run();
6923 }
6924
Jorim Jaggid0752812018-10-16 16:07:20 +02006925 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006926 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006927 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006928 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006929 // If there was nothing to resume, and we are not already restarting
6930 // this process, but there is a visible activity that is hosted by the
6931 // process...then make sure all visible activities are running, taking
6932 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006933 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006934 !PRESERVE_WINDOWS);
6935 }
6936 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006937 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006939 }
6940 }
6941 }
6942
6943 @Override
6944 public void closeSystemDialogs(String reason) {
6945 enforceNotIsolatedCaller("closeSystemDialogs");
6946
6947 final int pid = Binder.getCallingPid();
6948 final int uid = Binder.getCallingUid();
6949 final long origId = Binder.clearCallingIdentity();
6950 try {
6951 synchronized (mGlobalLock) {
6952 // Only allow this from foreground processes, so that background
6953 // applications can't abuse it to prevent system UI from being shown.
6954 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006955 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 if (!proc.isPerceptible()) {
6957 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6958 + " from background process " + proc);
6959 return;
6960 }
6961 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 mWindowManager.closeSystemDialogs(reason);
6963
Louis Chang149d5c82019-12-30 09:47:39 +08006964 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006965 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006966 // Call into AM outside the synchronized block.
6967 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006968 } finally {
6969 Binder.restoreCallingIdentity(origId);
6970 }
6971 }
6972
6973 @Override
6974 public void cleanupDisabledPackageComponents(
6975 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6976 synchronized (mGlobalLock) {
6977 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006978 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006979 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006980 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006981 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006982 }
6983
6984 // Clean-up disabled tasks
6985 getRecentTasks().cleanupDisabledPackageTasksLocked(
6986 packageName, disabledClasses, userId);
6987 }
6988 }
6989
6990 @Override
6991 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6992 int userId) {
6993 synchronized (mGlobalLock) {
6994
6995 boolean didSomething =
6996 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006997 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006998 null, doit, evenPersistent, userId);
6999 return didSomething;
7000 }
7001 }
7002
7003 @Override
7004 public void resumeTopActivities(boolean scheduleIdle) {
7005 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007006 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007007 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08007008 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007009 }
7010 }
7011 }
7012
Riddle Hsua0536432019-02-16 00:38:59 +08007013 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 @Override
7015 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08007016 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007017 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
7018 }
7019 }
7020
Riddle Hsua0536432019-02-16 00:38:59 +08007021 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007022 @Override
7023 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08007024 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007025 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
7026 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
7027 }
7028 try {
Louis Chang149d5c82019-12-30 09:47:39 +08007029 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08007030 } finally {
7031 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
7032 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07007033 }
7034 }
7035
7036 @Override
7037 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
7038 try {
7039 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
7040 throw new SecurityException("Only privileged app can call notifyLockedProfile");
7041 }
7042 } catch (RemoteException ex) {
7043 throw new SecurityException("Fail to check is caller a privileged app", ex);
7044 }
7045
7046 synchronized (mGlobalLock) {
7047 final long ident = Binder.clearCallingIdentity();
7048 try {
7049 if (mAmInternal.shouldConfirmCredentials(userId)) {
7050 if (mKeyguardController.isKeyguardLocked()) {
7051 // Showing launcher to avoid user entering credential twice.
7052 startHomeActivity(currentUserId, "notifyLockedProfile");
7053 }
Louis Chang149d5c82019-12-30 09:47:39 +08007054 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007055 }
7056 } finally {
7057 Binder.restoreCallingIdentity(ident);
7058 }
7059 }
7060 }
7061
7062 @Override
7063 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7064 mAmInternal.enforceCallingPermission(
7065 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7066
7067 synchronized (mGlobalLock) {
7068 final long ident = Binder.clearCallingIdentity();
7069 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007070 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7071 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007073 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7074 UserHandle.CURRENT);
7075 } finally {
7076 Binder.restoreCallingIdentity(ident);
7077 }
7078 }
7079 }
7080
7081 @Override
7082 public void writeActivitiesToProto(ProtoOutputStream proto) {
7083 synchronized (mGlobalLock) {
7084 // The output proto of "activity --proto activities"
7085 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007086 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007087 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7088 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007089 }
7090 }
7091
7092 @Override
7093 public void saveANRState(String reason) {
7094 synchronized (mGlobalLock) {
7095 final StringWriter sw = new StringWriter();
7096 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7097 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7098 if (reason != null) {
7099 pw.println(" Reason: " + reason);
7100 }
7101 pw.println();
7102 getActivityStartController().dump(pw, " ", null);
7103 pw.println();
7104 pw.println("-------------------------------------------------------------------------------");
7105 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7106 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7107 "" /* header */);
7108 pw.println();
7109 pw.close();
7110
7111 mLastANRState = sw.toString();
7112 }
7113 }
7114
7115 @Override
7116 public void clearSavedANRState() {
7117 synchronized (mGlobalLock) {
7118 mLastANRState = null;
7119 }
7120 }
7121
7122 @Override
7123 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7124 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7125 synchronized (mGlobalLock) {
7126 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7127 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7128 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7129 dumpLastANRLocked(pw);
7130 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7131 dumpLastANRTracesLocked(pw);
7132 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7133 dumpActivityStarterLocked(pw, dumpPackage);
7134 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7135 dumpActivityContainersLocked(pw);
7136 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7137 if (getRecentTasks() != null) {
7138 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7139 }
7140 }
7141 }
7142 }
7143
7144 @Override
7145 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7146 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7147 int wakefulness) {
7148 synchronized (mGlobalLock) {
7149 if (mHomeProcess != null && (dumpPackage == null
7150 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7151 if (needSep) {
7152 pw.println();
7153 needSep = false;
7154 }
7155 pw.println(" mHomeProcess: " + mHomeProcess);
7156 }
7157 if (mPreviousProcess != null && (dumpPackage == null
7158 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7159 if (needSep) {
7160 pw.println();
7161 needSep = false;
7162 }
7163 pw.println(" mPreviousProcess: " + mPreviousProcess);
7164 }
7165 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7166 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7167 StringBuilder sb = new StringBuilder(128);
7168 sb.append(" mPreviousProcessVisibleTime: ");
7169 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7170 pw.println(sb);
7171 }
7172 if (mHeavyWeightProcess != null && (dumpPackage == null
7173 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7174 if (needSep) {
7175 pw.println();
7176 needSep = false;
7177 }
7178 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7179 }
7180 if (dumpPackage == null) {
7181 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007182 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184 if (dumpAll) {
7185 if (dumpPackage == null) {
7186 pw.println(" mConfigWillChange: "
7187 + getTopDisplayFocusedStack().mConfigWillChange);
7188 }
7189 if (mCompatModePackages.getPackages().size() > 0) {
7190 boolean printed = false;
7191 for (Map.Entry<String, Integer> entry
7192 : mCompatModePackages.getPackages().entrySet()) {
7193 String pkg = entry.getKey();
7194 int mode = entry.getValue();
7195 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7196 continue;
7197 }
7198 if (!printed) {
7199 pw.println(" mScreenCompatPackages:");
7200 printed = true;
7201 }
7202 pw.println(" " + pkg + ": " + mode);
7203 }
7204 }
7205 }
7206
7207 if (dumpPackage == null) {
7208 pw.println(" mWakefulness="
7209 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007210 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007211 if (mRunningVoice != null) {
7212 pw.println(" mRunningVoice=" + mRunningVoice);
7213 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7214 }
7215 pw.println(" mSleeping=" + mSleeping);
7216 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7217 pw.println(" mVrController=" + mVrController);
7218 }
7219 if (mCurAppTimeTracker != null) {
7220 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7221 }
7222 if (mAllowAppSwitchUids.size() > 0) {
7223 boolean printed = false;
7224 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7225 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7226 for (int j = 0; j < types.size(); j++) {
7227 if (dumpPackage == null ||
7228 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7229 if (needSep) {
7230 pw.println();
7231 needSep = false;
7232 }
7233 if (!printed) {
7234 pw.println(" mAllowAppSwitchUids:");
7235 printed = true;
7236 }
7237 pw.print(" User ");
7238 pw.print(mAllowAppSwitchUids.keyAt(i));
7239 pw.print(": Type ");
7240 pw.print(types.keyAt(j));
7241 pw.print(" = ");
7242 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7243 pw.println();
7244 }
7245 }
7246 }
7247 }
7248 if (dumpPackage == null) {
7249 if (mController != null) {
7250 pw.println(" mController=" + mController
7251 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7252 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007253 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7254 pw.println(" mLaunchingActivityWakeLock="
7255 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007256 }
7257
7258 return needSep;
7259 }
7260 }
7261
7262 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007263 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7264 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007265 synchronized (mGlobalLock) {
7266 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007267 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007268 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007269 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7270 if (mRunningVoice != null) {
7271 final long vrToken = proto.start(
7272 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7273 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7274 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007275 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007276 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7277 proto.end(vrToken);
7278 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007279 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007280 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007281 if (mController != null) {
7282 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007283 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7284 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007285 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7286 proto.end(token);
7287 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007288 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7289 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007290 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007291 }
7292
7293 if (mHomeProcess != null && (dumpPackage == null
7294 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007295 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007296 }
7297
7298 if (mPreviousProcess != null && (dumpPackage == null
7299 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007300 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007301 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7302 }
7303
7304 if (mHeavyWeightProcess != null && (dumpPackage == null
7305 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007306 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007307 }
7308
7309 for (Map.Entry<String, Integer> entry
7310 : mCompatModePackages.getPackages().entrySet()) {
7311 String pkg = entry.getKey();
7312 int mode = entry.getValue();
7313 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7314 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7315 proto.write(PACKAGE, pkg);
7316 proto.write(MODE, mode);
7317 proto.end(compatToken);
7318 }
7319 }
7320
7321 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007322 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007323 }
7324
7325 }
7326 }
7327
7328 @Override
7329 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7330 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7331 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007332 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7333 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007334 }
7335
7336 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007337 public void dumpForOom(PrintWriter pw) {
7338 synchronized (mGlobalLock) {
7339 pw.println(" mHomeProcess: " + mHomeProcess);
7340 pw.println(" mPreviousProcess: " + mPreviousProcess);
7341 if (mHeavyWeightProcess != null) {
7342 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7343 }
7344 }
7345 }
7346
7347 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007348 public boolean canGcNow() {
7349 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007350 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007351 }
7352 }
7353
Riddle Hsua0536432019-02-16 00:38:59 +08007354 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007355 @Override
7356 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007357 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007358 if (mRootWindowContainer == null) {
7359 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007360 // oomadj after AMS created.
7361 return null;
7362 }
Louis Chang149d5c82019-12-30 09:47:39 +08007363 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007364 return top != null ? top.app : null;
7365 }
7366 }
7367
Riddle Hsua0536432019-02-16 00:38:59 +08007368 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007369 @Override
7370 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007371 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007372 if (mRootWindowContainer != null) {
7373 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007374 }
7375 }
7376 }
7377
7378 @Override
7379 public void scheduleDestroyAllActivities(String reason) {
7380 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007381 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007382 }
7383 }
7384
7385 @Override
7386 public void removeUser(int userId) {
7387 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007388 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007389 }
7390 }
7391
7392 @Override
7393 public boolean switchUser(int userId, UserState userState) {
7394 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007395 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007396 }
7397 }
7398
7399 @Override
7400 public void onHandleAppCrash(WindowProcessController wpc) {
7401 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007402 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007403 }
7404 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007405
7406 @Override
7407 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7408 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007409 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007410 }
7411 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007412
Riddle Hsua0536432019-02-16 00:38:59 +08007413 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007414 @Override
7415 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007416 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007417 }
7418
Riddle Hsua0536432019-02-16 00:38:59 +08007419 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007420 @Override
7421 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007422 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007423 }
7424
Riddle Hsua0536432019-02-16 00:38:59 +08007425 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007426 @Override
7427 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007428 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007429 }
7430
Riddle Hsua0536432019-02-16 00:38:59 +08007431 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007432 @Override
7433 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007434 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007435 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007436
7437 @Override
7438 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007439 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007440 mPendingTempWhitelist.put(uid, tag);
7441 }
7442 }
7443
7444 @Override
7445 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007446 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007447 mPendingTempWhitelist.remove(uid);
7448 }
7449 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007450
7451 @Override
7452 public boolean handleAppCrashInActivityController(String processName, int pid,
7453 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7454 Runnable killCrashingAppCallback) {
7455 synchronized (mGlobalLock) {
7456 if (mController == null) {
7457 return false;
7458 }
7459
7460 try {
7461 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7462 stackTrace)) {
7463 killCrashingAppCallback.run();
7464 return true;
7465 }
7466 } catch (RemoteException e) {
7467 mController = null;
7468 Watchdog.getInstance().setActivityController(null);
7469 }
7470 return false;
7471 }
7472 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007473
7474 @Override
7475 public void removeRecentTasksByPackageName(String packageName, int userId) {
7476 synchronized (mGlobalLock) {
7477 mRecentTasks.removeTasksByPackageName(packageName, userId);
7478 }
7479 }
7480
7481 @Override
7482 public void cleanupRecentTasksForUser(int userId) {
7483 synchronized (mGlobalLock) {
7484 mRecentTasks.cleanupLocked(userId);
7485 }
7486 }
7487
7488 @Override
7489 public void loadRecentTasksForUser(int userId) {
7490 synchronized (mGlobalLock) {
7491 mRecentTasks.loadUserRecentsLocked(userId);
7492 }
7493 }
7494
7495 @Override
7496 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7497 synchronized (mGlobalLock) {
7498 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7499 }
7500 }
7501
7502 @Override
7503 public void flushRecentTasks() {
7504 mRecentTasks.flush();
7505 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007506
7507 @Override
7508 public WindowProcessController getHomeProcess() {
7509 synchronized (mGlobalLock) {
7510 return mHomeProcess;
7511 }
7512 }
7513
7514 @Override
7515 public WindowProcessController getPreviousProcess() {
7516 synchronized (mGlobalLock) {
7517 return mPreviousProcess;
7518 }
7519 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007520
7521 @Override
7522 public void clearLockedTasks(String reason) {
7523 synchronized (mGlobalLock) {
7524 getLockTaskController().clearLockedTasks(reason);
7525 }
7526 }
7527
7528 @Override
7529 public void updateUserConfiguration() {
7530 synchronized (mGlobalLock) {
7531 final Configuration configuration = new Configuration(getGlobalConfiguration());
7532 final int currentUserId = mAmInternal.getCurrentUserId();
7533 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7534 configuration, currentUserId, Settings.System.canWrite(mContext));
7535 updateConfigurationLocked(configuration, null /* starting */,
7536 false /* initLocale */, false /* persistent */, currentUserId,
7537 false /* deferResume */);
7538 }
7539 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007540
7541 @Override
7542 public boolean canShowErrorDialogs() {
7543 synchronized (mGlobalLock) {
7544 return mShowDialogs && !mSleeping && !mShuttingDown
7545 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7546 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7547 mAmInternal.getCurrentUserId())
7548 && !(UserManager.isDeviceInDemoMode(mContext)
7549 && mAmInternal.getCurrentUser().isDemo());
7550 }
7551 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007552
7553 @Override
7554 public void setProfileApp(String profileApp) {
7555 synchronized (mGlobalLock) {
7556 mProfileApp = profileApp;
7557 }
7558 }
7559
7560 @Override
7561 public void setProfileProc(WindowProcessController wpc) {
7562 synchronized (mGlobalLock) {
7563 mProfileProc = wpc;
7564 }
7565 }
7566
7567 @Override
7568 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7569 synchronized (mGlobalLock) {
7570 mProfilerInfo = profilerInfo;
7571 }
7572 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007573
7574 @Override
7575 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7576 synchronized (mGlobalLock) {
7577 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7578 }
7579 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007580
7581 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007582 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7583 boolean reducedResolution) {
7584 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7585 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007586 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007587
7588 @Override
7589 public boolean isUidForeground(int uid) {
7590 synchronized (mGlobalLock) {
7591 return ActivityTaskManagerService.this.isUidForeground(uid);
7592 }
7593 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007594
7595 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007596 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007597 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007598 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007599 }
7600 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007601
7602 @Override
7603 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007604 // Translate package names into UIDs
7605 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007606 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007607 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7608 if (uid >= 0) {
7609 result.add(uid);
7610 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007611 }
7612 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007613 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007614 }
7615 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007616 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007617}