blob: 8bccbbfba0effa4aca0dd036d64715623d749f7e [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080055import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070067
Yunfan Chen79b96062018-10-17 12:45:23 -070068import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
69import static com.android.server.am.ActivityManagerService.MY_PID;
70import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
71import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070072import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Jeff Changd136e772019-11-05 20:33:52 +080086import static com.android.server.am.EventLogTags.writeBootProgressEnableScreen;
87import static com.android.server.am.EventLogTags.writeConfigurationChanged;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070088import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
89import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Louis Chang149d5c82019-12-30 09:47:39 +0800120import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootWindowContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
Louis Changcdec0802019-11-11 11:45:07 +0800122import static com.android.server.wm.Task.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.Task.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.Task.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800127import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700128import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.annotation.Nullable;
130import android.annotation.UserIdInt;
131import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700132import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.app.ActivityOptions;
135import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700136import android.app.ActivityThread;
137import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700138import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100139import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700140import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700141import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700142import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.IApplicationThread;
144import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400146import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700159import android.app.servertransaction.ClientTransaction;
160import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700161import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.ActivityNotFoundException;
163import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700165import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.IIntentSender;
168import android.content.Intent;
169import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700170import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900171import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.pm.ParceledListSlice;
176import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700177import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700179import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700180import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.graphics.Bitmap;
182import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.metrics.LogMaker;
185import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700186import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700189import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700190import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700194import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800195import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700199import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100200import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
214import android.service.voice.IVoiceInteractionSession;
215import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900216import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700217import android.telecom.TelecomManager;
218import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100219import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700221import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700223import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.SparseArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Roskyddedfd42019-10-04 13:38:38 -0700231import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700233
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700235import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700237import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700239import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700242import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
243import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700245import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700246import com.android.internal.policy.IKeyguardDismissCallback;
247import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700248import com.android.internal.util.ArrayUtils;
249import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700250import com.android.internal.util.Preconditions;
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800251import com.android.internal.util.function.pooled.PooledConsumer;
252import com.android.internal.util.function.pooled.PooledFunction;
Wale Ogunwale53783742018-09-16 10:21:51 -0700253import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700254import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700255import com.android.server.LocalServices;
256import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700257import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800258import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700259import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700260import com.android.server.am.ActivityManagerService;
261import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
262import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
263import com.android.server.am.AppTimeTracker;
264import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700265import com.android.server.am.PendingIntentController;
266import com.android.server.am.PendingIntentRecord;
267import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900268import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700269import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700270import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800272import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700273import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700274import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700277import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700280import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700281import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700282import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700283import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800284import java.lang.annotation.ElementType;
285import java.lang.annotation.Retention;
286import java.lang.annotation.RetentionPolicy;
287import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700291import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400293import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700294import java.util.HashSet;
Evan Roskyddedfd42019-10-04 13:38:38 -0700295import java.util.Iterator;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700297import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700298import java.util.Map;
299import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700300
301/**
302 * System service for managing activities and their containers (task, stacks, displays,... ).
303 *
304 * {@hide}
305 */
306public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000309 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700310 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
311 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
312 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
313 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700314 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700315
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700319 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100320 // How long we permit background activity starts after an activity in the process
321 // started or finished.
322 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700323
Wale Ogunwale98875612018-10-12 07:53:02 -0700324 /** Used to indicate that an app transition should be animated. */
325 static final boolean ANIMATE = true;
326
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700327 /** Hardware-reported OpenGLES version. */
328 final int GL_ES_VERSION;
329
Wale Ogunwale31913b52018-10-13 08:29:31 -0700330 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
331 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
332 public static final String DUMP_LASTANR_CMD = "lastanr" ;
333 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
334 public static final String DUMP_STARTER_CMD = "starter" ;
335 public static final String DUMP_CONTAINERS_CMD = "containers" ;
336 public static final String DUMP_RECENTS_CMD = "recents" ;
337 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
338
Wale Ogunwale64258362018-10-16 15:13:37 -0700339 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
340 public static final int RELAUNCH_REASON_NONE = 0;
341 /** This activity is being relaunched due to windowing mode change. */
342 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
343 /** This activity is being relaunched due to a free-resize operation. */
344 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
345
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700346 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700347
Wale Ogunwalef6733932018-06-27 05:14:34 -0700348 /**
349 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
350 * change at runtime. Use mContext for non-UI purposes.
351 */
352 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700355 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700356 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700357 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700358 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800359 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800360 @VisibleForTesting
361 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700362 PowerManagerInternal mPowerManagerInternal;
363 private UsageStatsManagerInternal mUsageStatsInternal;
364
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700365 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700366 IntentFirewall mIntentFirewall;
367
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700368 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800369 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700371 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800372 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
373 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
374 *
375 * @see WindowManagerThreadPriorityBooster
376 */
377 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800379 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700380 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700381 private UserManagerService mUserManager;
382 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700383 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800384 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700385 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700386 /** All processes currently running that might have a window organized by name. */
387 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100388 /** All processes we currently have running mapped by pid and uid */
389 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /** This is the process holding what we currently consider to be the "home" activity. */
391 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700392 /** The currently running heavy-weight process, if any. */
393 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700394 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700395 /**
396 * This is the process holding the activity the user last visited that is in a different process
397 * from the one they are currently in.
398 */
399 WindowProcessController mPreviousProcess;
400 /** The time at which the previous process was last visible. */
401 long mPreviousProcessVisibleTime;
402
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700403 /** List of intents that were used to start the most recent tasks. */
404 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700405 /** State of external calls telling us if the device is awake or asleep. */
406 private boolean mKeyguardShown = false;
407
408 // Wrapper around VoiceInteractionServiceManager
409 private AssistUtils mAssistUtils;
410
411 // VoiceInteraction session ID that changes for each new request except when
412 // being called for multi-window assist in a single session.
413 private int mViSessionId = 1000;
414
415 // How long to wait in getAssistContextExtras for the activity and foreground services
416 // to respond with the result.
417 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
418
419 // How long top wait when going through the modern assist (which doesn't need to block
420 // on getting this result before starting to launch its UI).
421 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
422
423 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
424 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
425
Alison Cichowlas3e340502018-08-07 17:15:01 -0400426 // Permission tokens are used to temporarily granted a trusted app the ability to call
427 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
428 // showing any appropriate error messages to the user.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
430 10 * MINUTE_IN_MILLIS;
431
432 // How long before the service actually expires a token. This is slightly longer than
433 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
434 // expiration exception.
435 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
436 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
437
438 // How long the service will remember expired tokens, for the purpose of providing error
439 // messaging when a client uses an expired token.
440 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
441 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
442
443 // Activity tokens of system activities that are delegating their call to
444 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
445 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
446
447 // Permission tokens that have expired, but we remember for error reporting.
448 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
449
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700450 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
451
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 // Keeps track of the active voice interaction service component, notified from
453 // VoiceInteractionManagerService
454 ComponentName mActiveVoiceInteractionServiceComponent;
455
Michal Karpinskida34cd42019-04-02 19:46:52 +0100456 // A map userId and all its companion app uids
457 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000458
Wale Ogunwalee2172292018-10-25 10:11:10 -0700459 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460 KeyguardController mKeyguardController;
461 private final ClientLifecycleManager mLifecycleManager;
462 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700463 /** The controller for all operations related to locktask. */
464 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700465 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700466
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700467 boolean mSuppressResizeConfigChanges;
468
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700469 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700470 new UpdateConfigurationResult();
471
472 static final class UpdateConfigurationResult {
473 // Configuration changes that were updated.
474 int changes;
475 // If the activity was relaunched to match the new configuration.
476 boolean activityRelaunched;
477
478 void reset() {
479 changes = 0;
480 activityRelaunched = false;
481 }
482 }
483
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700484 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485 private int mConfigurationSeq;
486 // To cache the list of supported system locales
487 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700488
489 /**
490 * Temp object used when global and/or display override configuration is updated. It is also
491 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
492 * anyone...
493 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 private Configuration mTempConfig = new Configuration();
495
Wale Ogunwalef6733932018-06-27 05:14:34 -0700496 /** Temporary to avoid allocations. */
497 final StringBuilder mStringBuilder = new StringBuilder(256);
498
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700499 // Amount of time after a call to stopAppSwitches() during which we will
500 // prevent further untrusted switches from happening.
501 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
502
503 /**
504 * The time at which we will allow normal application switches again,
505 * after a call to {@link #stopAppSwitches()}.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
509 * This is set to true after the first switch after mAppSwitchesAllowedTime
510 * is set; any switches after that will clear the time.
511 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700512 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513
Ricky Wai906af482019-06-03 17:25:28 +0100514 /**
515 * Last stop app switches time, apps finished before this time cannot start background activity
516 * even if they are in grace period.
517 */
518 private long mLastStopAppSwitchesTime;
519
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700520 IActivityController mController = null;
521 boolean mControllerIsAMonkey = false;
522
Wale Ogunwale214f3482018-10-04 11:00:47 -0700523 final int mFactoryTest;
524
525 /** Used to control how we initialize the service. */
526 ComponentName mTopComponent;
527 String mTopAction = Intent.ACTION_MAIN;
528 String mTopData;
529
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800530 /** Profiling app information. */
531 String mProfileApp = null;
532 WindowProcessController mProfileProc = null;
533 ProfilerInfo mProfilerInfo = null;
534
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700536 * Dump of the activity state at the time of the last ANR. Cleared after
537 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
538 */
539 String mLastANRState;
540
541 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700542 * Used to retain an update lock when the foreground activity is in
543 * immersive mode.
544 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700545 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700546
547 /**
548 * Packages that are being allowed to perform unrestricted app switches. Mapping is
549 * User -> Type -> uid.
550 */
551 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
552
553 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700554 private int mThumbnailWidth;
555 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700556
557 /**
558 * Flag that indicates if multi-window is enabled.
559 *
560 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
561 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
562 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
563 * At least one of the forms of multi-window must be enabled in order for this flag to be
564 * initialized to 'true'.
565 *
566 * @see #mSupportsSplitScreenMultiWindow
567 * @see #mSupportsFreeformWindowManagement
568 * @see #mSupportsPictureInPicture
569 * @see #mSupportsMultiDisplay
570 */
571 boolean mSupportsMultiWindow;
572 boolean mSupportsSplitScreenMultiWindow;
573 boolean mSupportsFreeformWindowManagement;
574 boolean mSupportsPictureInPicture;
575 boolean mSupportsMultiDisplay;
576 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700577 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700578
579 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
580
581 // VR Vr2d Display Id.
582 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700583
Wale Ogunwalef6733932018-06-27 05:14:34 -0700584 /**
585 * Set while we are wanting to sleep, to prevent any
586 * activities from being started/resumed.
587 *
588 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
589 *
590 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
591 * while in the sleep state until there is a pending transition out of sleep, in which case
592 * mSleeping is set to false, and remains false while awake.
593 *
594 * Whether mSleeping can quickly toggled between true/false without the device actually
595 * display changing states is undefined.
596 */
597 private boolean mSleeping = false;
598
599 /**
600 * The process state used for processes that are running the top activities.
601 * This changes between TOP and TOP_SLEEPING to following mSleeping.
602 */
603 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
604
Riddle Hsua0022cd2019-09-09 21:12:41 +0800605 @Retention(RetentionPolicy.SOURCE)
606 @IntDef({
607 LAYOUT_REASON_CONFIG_CHANGED,
608 LAYOUT_REASON_VISIBILITY_CHANGED,
609 })
610 @interface LayoutReason {}
611 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
612 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
613
614 /** The reasons to perform surface placement. */
615 @LayoutReason
616 private int mLayoutReasons;
617
Wale Ogunwalef6733932018-06-27 05:14:34 -0700618 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
619 // automatically. Important for devices without direct input devices.
620 private boolean mShowDialogs = true;
621
622 /** Set if we are shutting down the system, similar to sleeping. */
623 boolean mShuttingDown = false;
624
625 /**
626 * We want to hold a wake lock while running a voice interaction session, since
627 * this may happen with the screen off and we need to keep the CPU running to
628 * be able to continue to interact with the user.
629 */
630 PowerManager.WakeLock mVoiceWakeLock;
631
632 /**
633 * Set while we are running a voice interaction. This overrides sleeping while it is active.
634 */
635 IVoiceInteractionSession mRunningVoice;
636
637 /**
638 * The last resumed activity. This is identical to the current resumed activity most
639 * of the time but could be different when we're pausing one activity before we resume
640 * another activity.
641 */
642 ActivityRecord mLastResumedActivity;
643
644 /**
645 * The activity that is currently being traced as the active resumed activity.
646 *
647 * @see #updateResumedAppTrace
648 */
649 private @Nullable ActivityRecord mTracedResumedActivity;
650
651 /** If non-null, we are tracking the time the user spends in the currently focused app. */
652 AppTimeTracker mCurAppTimeTracker;
653
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700654 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700655
Wale Ogunwale53783742018-09-16 10:21:51 -0700656 /**
657 * Packages that the user has asked to have run in screen size
658 * compatibility mode instead of filling the screen.
659 */
660 CompatModePackages mCompatModePackages;
661
Wale Ogunwalef6733932018-06-27 05:14:34 -0700662 private FontScaleSettingObserver mFontScaleSettingObserver;
663
Ricky Wai96f5c352019-04-10 18:40:17 +0100664 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000665
Wale Ogunwalef6733932018-06-27 05:14:34 -0700666 private final class FontScaleSettingObserver extends ContentObserver {
667 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
668 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
669
670 public FontScaleSettingObserver() {
671 super(mH);
672 final ContentResolver resolver = mContext.getContentResolver();
673 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
674 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
675 UserHandle.USER_ALL);
676 }
677
678 @Override
679 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
680 if (mFontScaleUri.equals(uri)) {
681 updateFontScaleIfNeeded(userId);
682 } else if (mHideErrorDialogsUri.equals(uri)) {
683 synchronized (mGlobalLock) {
684 updateShouldShowDialogsLocked(getGlobalConfiguration());
685 }
686 }
687 }
688 }
689
Riddle Hsua0536432019-02-16 00:38:59 +0800690 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
691 @Target(ElementType.METHOD)
692 @Retention(RetentionPolicy.SOURCE)
693 @interface HotPath {
694 int NONE = 0;
695 int OOM_ADJUSTMENT = 1;
696 int LRU_UPDATE = 2;
697 int PROCESS_CHANGE = 3;
698 int caller() default NONE;
699 }
700
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800701 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
702 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900703 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800704 mAmInternal.updateOomAdj();
705 }
706 };
707
Charles Chen8d98dd22018-12-26 17:36:54 +0800708 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
709 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700710 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700711 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700712 mSystemThread = ActivityThread.currentActivityThread();
713 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700714 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800715 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700716 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700717 }
718
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700719 public void onSystemReady() {
720 synchronized (mGlobalLock) {
721 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
722 PackageManager.FEATURE_CANT_SAVE_STATE);
723 mAssistUtils = new AssistUtils(mContext);
724 mVrController.onSystemReady();
725 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700726 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700728 }
729
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 public void onInitPowerManagement() {
731 synchronized (mGlobalLock) {
732 mStackSupervisor.initPowerManagement();
733 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
734 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
735 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
736 mVoiceWakeLock.setReferenceCounted(false);
737 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700738 }
739
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700740 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700741 mFontScaleSettingObserver = new FontScaleSettingObserver();
742 }
743
Wale Ogunwale59507092018-10-29 09:00:30 -0700744 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700745 final boolean freeformWindowManagement =
746 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
747 || Settings.Global.getInt(
748 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
749
750 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
751 final boolean supportsPictureInPicture = supportsMultiWindow &&
752 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
753 final boolean supportsSplitScreenMultiWindow =
754 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
755 final boolean supportsMultiDisplay = mContext.getPackageManager()
756 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700757 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
758 final boolean forceResizable = Settings.Global.getInt(
759 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700760 final boolean sizeCompatFreeform = Settings.Global.getInt(
761 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700762
763 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900764 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765
766 final Configuration configuration = new Configuration();
767 Settings.System.getConfiguration(resolver, configuration);
768 if (forceRtl) {
769 // This will take care of setting the correct layout direction flags
770 configuration.setLayoutDirection(configuration.locale);
771 }
772
773 synchronized (mGlobalLock) {
774 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700775 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700776 final boolean multiWindowFormEnabled = freeformWindowManagement
777 || supportsSplitScreenMultiWindow
778 || supportsPictureInPicture
779 || supportsMultiDisplay;
780 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
781 mSupportsMultiWindow = true;
782 mSupportsFreeformWindowManagement = freeformWindowManagement;
783 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
784 mSupportsPictureInPicture = supportsPictureInPicture;
785 mSupportsMultiDisplay = supportsMultiDisplay;
786 } else {
787 mSupportsMultiWindow = false;
788 mSupportsFreeformWindowManagement = false;
789 mSupportsSplitScreenMultiWindow = false;
790 mSupportsPictureInPicture = false;
791 mSupportsMultiDisplay = false;
792 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700793 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700794 // This happens before any activities are started, so we can change global configuration
795 // in-place.
796 updateConfigurationLocked(configuration, null, true);
797 final Configuration globalConfig = getGlobalConfiguration();
798 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
799
800 // Load resources only after the current configuration has been set.
801 final Resources res = mContext.getResources();
802 mThumbnailWidth = res.getDimensionPixelSize(
803 com.android.internal.R.dimen.thumbnail_width);
804 mThumbnailHeight = res.getDimensionPixelSize(
805 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 }
807 }
808
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800809 public WindowManagerGlobalLock getGlobalLock() {
810 return mGlobalLock;
811 }
812
Yunfan Chen585f2932019-01-29 16:04:45 +0900813 /** For test purpose only. */
814 @VisibleForTesting
815 public ActivityTaskManagerInternal getAtmInternal() {
816 return mInternal;
817 }
818
Riddle Hsud93a6c42018-11-29 21:50:06 +0800819 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
820 Looper looper) {
821 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700824 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800825 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700826 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700827 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700828 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700830 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700832 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700833 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700834 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700835 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700836 mKeyguardController = mStackSupervisor.getKeyguardController();
837 }
838
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700839 public void onActivityManagerInternalAdded() {
840 synchronized (mGlobalLock) {
841 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
842 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
843 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700844 }
845
Yunfan Chen75157d72018-07-27 14:47:21 +0900846 int increaseConfigurationSeqLocked() {
847 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
848 return mConfigurationSeq;
849 }
850
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700851 protected ActivityStackSupervisor createStackSupervisor() {
852 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
853 supervisor.initialize();
854 return supervisor;
855 }
856
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800857 protected AppWarnings createAppWarnings(
858 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
859 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
860 }
861
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700862 public void setWindowManager(WindowManagerService wm) {
863 synchronized (mGlobalLock) {
864 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800865 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800866 mTempConfig.setToDefaults();
867 mTempConfig.setLocales(LocaleList.getDefault());
868 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800869 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700870 mLockTaskController.setWindowManager(wm);
871 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800872 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700874 }
875
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700876 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
877 synchronized (mGlobalLock) {
878 mUsageStatsInternal = usageStatsManager;
879 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700880 }
881
Wale Ogunwalef6733932018-06-27 05:14:34 -0700882 UserManagerService getUserManager() {
883 if (mUserManager == null) {
884 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
885 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
886 }
887 return mUserManager;
888 }
889
890 AppOpsService getAppOpsService() {
891 if (mAppOpsService == null) {
892 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
893 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
894 }
895 return mAppOpsService;
896 }
897
898 boolean hasUserRestriction(String restriction, int userId) {
899 return getUserManager().hasUserRestriction(restriction, userId);
900 }
901
Michal Karpinski15486842019-04-25 17:33:42 +0100902 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
903 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700904 callingUid, callingPackage, /* featureId */ null);
Michal Karpinski15486842019-04-25 17:33:42 +0100905 if (mode == AppOpsManager.MODE_DEFAULT) {
906 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
907 == PERMISSION_GRANTED;
908 }
909 return mode == AppOpsManager.MODE_ALLOWED;
910 }
911
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700912 @VisibleForTesting
913 protected void setRecentTasks(RecentTasks recentTasks) {
914 mRecentTasks = recentTasks;
915 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700916 }
917
918 RecentTasks getRecentTasks() {
919 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 }
921
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700922 ClientLifecycleManager getLifecycleManager() {
923 return mLifecycleManager;
924 }
925
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700926 ActivityStartController getActivityStartController() {
927 return mActivityStartController;
928 }
929
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700930 TaskChangeNotificationController getTaskChangeNotificationController() {
931 return mTaskChangeNotificationController;
932 }
933
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700934 LockTaskController getLockTaskController() {
935 return mLockTaskController;
936 }
937
Yunfan Chen75157d72018-07-27 14:47:21 +0900938 /**
939 * Return the global configuration used by the process corresponding to the input pid. This is
940 * usually the global configuration with some overrides specific to that process.
941 */
942 Configuration getGlobalConfigurationForCallingPid() {
943 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800944 return getGlobalConfigurationForPid(pid);
945 }
946
947 /**
948 * Return the global configuration used by the process corresponding to the given pid.
949 */
950 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900951 if (pid == MY_PID || pid < 0) {
952 return getGlobalConfiguration();
953 }
954 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100955 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900956 return app != null ? app.getConfiguration() : getGlobalConfiguration();
957 }
958 }
959
960 /**
961 * Return the device configuration info used by the process corresponding to the input pid.
962 * The value is consistent with the global configuration for the process.
963 */
964 @Override
965 public ConfigurationInfo getDeviceConfigurationInfo() {
966 ConfigurationInfo config = new ConfigurationInfo();
967 synchronized (mGlobalLock) {
968 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
969 config.reqTouchScreen = globalConfig.touchscreen;
970 config.reqKeyboardType = globalConfig.keyboard;
971 config.reqNavigation = globalConfig.navigation;
972 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
973 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
974 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
975 }
976 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
977 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
978 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
979 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700980 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900981 }
982 return config;
983 }
984
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700985 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700986 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700987 }
988
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700989 public static final class Lifecycle extends SystemService {
990 private final ActivityTaskManagerService mService;
991
992 public Lifecycle(Context context) {
993 super(context);
994 mService = new ActivityTaskManagerService(context);
995 }
996
997 @Override
998 public void onStart() {
999 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001000 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001001 }
1002
Garfield Tan891146c2018-10-09 12:14:00 -07001003 @Override
1004 public void onUnlockUser(int userId) {
1005 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001006 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001007 }
1008 }
1009
1010 @Override
1011 public void onCleanupUser(int userId) {
1012 synchronized (mService.getGlobalLock()) {
1013 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1014 }
1015 }
1016
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001017 public ActivityTaskManagerService getService() {
1018 return mService;
1019 }
1020 }
1021
1022 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 public final int startActivity(IApplicationThread caller, String callingPackage,
1024 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1025 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1026 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1027 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1028 UserHandle.getCallingUserId());
1029 }
1030
1031 @Override
1032 public final int startActivities(IApplicationThread caller, String callingPackage,
1033 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1034 int userId) {
1035 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001036 enforceNotIsolatedCaller(reason);
1037 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001039 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1040 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1041 reason, null /* originatingPendingIntent */,
1042 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043 }
1044
1045 @Override
1046 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1047 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1048 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1049 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1050 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1051 true /*validateIncomingUser*/);
1052 }
1053
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001054 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1056 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1057 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001058 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001060 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1062
1063 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001064 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 .setCaller(caller)
1066 .setCallingPackage(callingPackage)
1067 .setResolvedType(resolvedType)
1068 .setResultTo(resultTo)
1069 .setResultWho(resultWho)
1070 .setRequestCode(requestCode)
1071 .setStartFlags(startFlags)
1072 .setProfilerInfo(profilerInfo)
1073 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001074 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 .execute();
1076
1077 }
1078
1079 @Override
1080 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1081 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001082 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1083 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 // Refuse possible leaked file descriptors
1085 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1086 throw new IllegalArgumentException("File descriptors passed in Intent");
1087 }
1088
1089 if (!(target instanceof PendingIntentRecord)) {
1090 throw new IllegalArgumentException("Bad PendingIntent object");
1091 }
1092
1093 PendingIntentRecord pir = (PendingIntentRecord)target;
1094
1095 synchronized (mGlobalLock) {
1096 // If this is coming from the currently resumed activity, it is
1097 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001098 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 if (stack.mResumedActivity != null &&
1100 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001101 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001102 }
1103 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001104 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001105 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 }
1107
1108 @Override
1109 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1110 Bundle bOptions) {
1111 // Refuse possible leaked file descriptors
1112 if (intent != null && intent.hasFileDescriptors()) {
1113 throw new IllegalArgumentException("File descriptors passed in Intent");
1114 }
1115 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1116
1117 synchronized (mGlobalLock) {
1118 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1119 if (r == null) {
1120 SafeActivityOptions.abort(options);
1121 return false;
1122 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001123 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 // The caller is not running... d'oh!
1125 SafeActivityOptions.abort(options);
1126 return false;
1127 }
1128 intent = new Intent(intent);
1129 // The caller is not allowed to change the data.
1130 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1131 // And we are resetting to find the next component...
1132 intent.setComponent(null);
1133
1134 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1135
1136 ActivityInfo aInfo = null;
1137 try {
1138 List<ResolveInfo> resolves =
1139 AppGlobals.getPackageManager().queryIntentActivities(
1140 intent, r.resolvedType,
1141 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1142 UserHandle.getCallingUserId()).getList();
1143
1144 // Look for the original activity in the list...
1145 final int N = resolves != null ? resolves.size() : 0;
1146 for (int i=0; i<N; i++) {
1147 ResolveInfo rInfo = resolves.get(i);
1148 if (rInfo.activityInfo.packageName.equals(r.packageName)
1149 && rInfo.activityInfo.name.equals(r.info.name)) {
1150 // We found the current one... the next matching is
1151 // after it.
1152 i++;
1153 if (i<N) {
1154 aInfo = resolves.get(i).activityInfo;
1155 }
1156 if (debug) {
1157 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1158 + "/" + r.info.name);
1159 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1160 ? "null" : aInfo.packageName + "/" + aInfo.name));
1161 }
1162 break;
1163 }
1164 }
1165 } catch (RemoteException e) {
1166 }
1167
1168 if (aInfo == null) {
1169 // Nobody who is next!
1170 SafeActivityOptions.abort(options);
1171 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1172 return false;
1173 }
1174
1175 intent.setComponent(new ComponentName(
1176 aInfo.applicationInfo.packageName, aInfo.name));
1177 intent.setFlags(intent.getFlags()&~(
1178 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1179 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1180 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1181 FLAG_ACTIVITY_NEW_TASK));
1182
1183 // Okay now we need to start the new activity, replacing the currently running activity.
1184 // This is a little tricky because we want to start the new one as if the current one is
1185 // finished, but not finish the current one first so that there is no flicker.
1186 // And thus...
1187 final boolean wasFinishing = r.finishing;
1188 r.finishing = true;
1189
1190 // Propagate reply information over to the new activity.
1191 final ActivityRecord resultTo = r.resultTo;
1192 final String resultWho = r.resultWho;
1193 final int requestCode = r.requestCode;
1194 r.resultTo = null;
1195 if (resultTo != null) {
1196 resultTo.removeResultsLocked(r, resultWho, requestCode);
1197 }
1198
1199 final long origId = Binder.clearCallingIdentity();
1200 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001201 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001202 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001203 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001204 .setResolvedType(r.resolvedType)
1205 .setActivityInfo(aInfo)
1206 .setResultTo(resultTo != null ? resultTo.appToken : null)
1207 .setResultWho(resultWho)
1208 .setRequestCode(requestCode)
1209 .setCallingPid(-1)
1210 .setCallingUid(r.launchedFromUid)
1211 .setCallingPackage(r.launchedFromPackage)
1212 .setRealCallingPid(-1)
1213 .setRealCallingUid(r.launchedFromUid)
1214 .setActivityOptions(options)
1215 .execute();
1216 Binder.restoreCallingIdentity(origId);
1217
1218 r.finishing = wasFinishing;
1219 if (res != ActivityManager.START_SUCCESS) {
1220 return false;
1221 }
1222 return true;
1223 }
1224 }
1225
1226 @Override
1227 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1228 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1229 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1230 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001231 enforceNotIsolatedCaller("startActivityAndWait");
1232 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1233 userId, "startActivityAndWait");
1234 // TODO: Switch to user app stacks here.
1235 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1236 .setCaller(caller)
1237 .setCallingPackage(callingPackage)
1238 .setResolvedType(resolvedType)
1239 .setResultTo(resultTo)
1240 .setResultWho(resultWho)
1241 .setRequestCode(requestCode)
1242 .setStartFlags(startFlags)
1243 .setActivityOptions(bOptions)
1244 .setUserId(userId)
1245 .setProfilerInfo(profilerInfo)
1246 .setWaitResult(res)
1247 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001248 return res;
1249 }
1250
1251 @Override
1252 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1253 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1254 int startFlags, Configuration config, Bundle bOptions, int userId) {
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001255 enforceNotIsolatedCaller("startActivityWithConfig");
1256 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1257 "startActivityWithConfig");
1258 // TODO: Switch to user app stacks here.
1259 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1260 .setCaller(caller)
1261 .setCallingPackage(callingPackage)
1262 .setResolvedType(resolvedType)
1263 .setResultTo(resultTo)
1264 .setResultWho(resultWho)
1265 .setRequestCode(requestCode)
1266 .setStartFlags(startFlags)
1267 .setGlobalConfiguration(config)
1268 .setActivityOptions(bOptions)
1269 .setUserId(userId)
1270 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 }
1272
Alison Cichowlas3e340502018-08-07 17:15:01 -04001273
1274 @Override
1275 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1276 int callingUid = Binder.getCallingUid();
1277 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1278 throw new SecurityException("Only the system process can request a permission token, "
1279 + "received request from uid: " + callingUid);
1280 }
1281 IBinder permissionToken = new Binder();
1282 synchronized (mGlobalLock) {
1283 mStartActivitySources.put(permissionToken, delegatorToken);
1284 }
1285
1286 Message expireMsg = PooledLambda.obtainMessage(
1287 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1288 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1289
1290 Message forgetMsg = PooledLambda.obtainMessage(
1291 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1292 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1293
1294 return permissionToken;
1295 }
1296
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 @Override
1298 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1299 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001300 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1301 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001302 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001303 // permission grants) as any app that may launch one of your own activities. So we only
1304 // allow this in two cases:
1305 // 1) The caller is an activity that is part of the core framework, and then only when it
1306 // is running as the system.
1307 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1308 // can only be requested by a system activity, which may then delegate this call to
1309 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 final ActivityRecord sourceRecord;
1311 final int targetUid;
1312 final String targetPackage;
1313 final boolean isResolver;
1314 synchronized (mGlobalLock) {
1315 if (resultTo == null) {
1316 throw new SecurityException("Must be called from an activity");
1317 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001318 final IBinder sourceToken;
1319 if (permissionToken != null) {
1320 // To even attempt to use a permissionToken, an app must also have this signature
1321 // permission.
1322 mAmInternal.enforceCallingPermission(
1323 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1324 "startActivityAsCaller");
1325 // If called with a permissionToken, we want the sourceRecord from the delegator
1326 // activity that requested this token.
1327 sourceToken = mStartActivitySources.remove(permissionToken);
1328 if (sourceToken == null) {
1329 // Invalid permissionToken, check if it recently expired.
1330 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1331 throw new SecurityException("Called with expired permission token: "
1332 + permissionToken);
1333 } else {
1334 throw new SecurityException("Called with invalid permission token: "
1335 + permissionToken);
1336 }
1337 }
1338 } else {
1339 // This method was called directly by the source.
1340 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001342
Louis Chang149d5c82019-12-30 09:47:39 +08001343 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001344 if (sourceRecord == null) {
1345 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001346 }
1347 if (sourceRecord.app == null) {
1348 throw new SecurityException("Called without a process attached to activity");
1349 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001350
1351 // Whether called directly or from a delegate, the source activity must be from the
1352 // android package.
1353 if (!sourceRecord.info.packageName.equals("android")) {
1354 throw new SecurityException("Must be called from an activity that is "
1355 + "declared in the android package");
1356 }
1357
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001358 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 // This is still okay, as long as this activity is running under the
1360 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001361 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001362 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001363 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 + " must be system uid or original calling uid "
1365 + sourceRecord.launchedFromUid);
1366 }
1367 }
1368 if (ignoreTargetSecurity) {
1369 if (intent.getComponent() == null) {
1370 throw new SecurityException(
1371 "Component must be specified with ignoreTargetSecurity");
1372 }
1373 if (intent.getSelector() != null) {
1374 throw new SecurityException(
1375 "Selector not allowed with ignoreTargetSecurity");
1376 }
1377 }
1378 targetUid = sourceRecord.launchedFromUid;
1379 targetPackage = sourceRecord.launchedFromPackage;
1380 isResolver = sourceRecord.isResolverOrChildActivity();
1381 }
1382
1383 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001384 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 }
1386
1387 // TODO: Switch to user app stacks here.
1388 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001389 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 .setCallingUid(targetUid)
1391 .setCallingPackage(targetPackage)
1392 .setResolvedType(resolvedType)
1393 .setResultTo(resultTo)
1394 .setResultWho(resultWho)
1395 .setRequestCode(requestCode)
1396 .setStartFlags(startFlags)
1397 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001398 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1400 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001401 // The target may well be in the background, which would normally prevent it
1402 // from starting an activity. Here we definitely want the start to succeed.
1403 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001404 .execute();
1405 } catch (SecurityException e) {
1406 // XXX need to figure out how to propagate to original app.
1407 // A SecurityException here is generally actually a fault of the original
1408 // calling activity (such as a fairly granting permissions), so propagate it
1409 // back to them.
1410 /*
1411 StringBuilder msg = new StringBuilder();
1412 msg.append("While launching");
1413 msg.append(intent.toString());
1414 msg.append(": ");
1415 msg.append(e.getMessage());
1416 */
1417 throw e;
1418 }
1419 }
1420
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001421 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1422 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1423 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1424 }
1425
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 @Override
1427 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1428 Intent intent, String resolvedType, IVoiceInteractionSession session,
1429 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1430 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001431 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001432 if (session == null || interactor == null) {
1433 throw new NullPointerException("null session or interactor");
1434 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001437 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 .setCallingUid(callingUid)
1439 .setCallingPackage(callingPackage)
1440 .setResolvedType(resolvedType)
1441 .setVoiceSession(session)
1442 .setVoiceInteractor(interactor)
1443 .setStartFlags(startFlags)
1444 .setProfilerInfo(profilerInfo)
1445 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001446 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001447 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001448 .execute();
1449 }
1450
1451 @Override
1452 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1453 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001454 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1455 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001457 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 .setCallingUid(callingUid)
1459 .setCallingPackage(callingPackage)
1460 .setResolvedType(resolvedType)
1461 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001462 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001463 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 .execute();
1465 }
1466
Riddle Hsu609a8e22019-06-27 16:46:29 -06001467 /**
1468 * Start the recents activity to perform the recents animation.
1469 *
1470 * @param intent The intent to start the recents activity.
1471 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1472 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001473 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001474 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1475 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001476 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001478 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 final long origId = Binder.clearCallingIdentity();
1480 try {
1481 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001482 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1483 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001484 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001485
1486 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001487 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001488 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001489 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001490 if (recentsAnimationRunner == null) {
1491 anim.preloadRecentsActivity();
1492 } else {
1493 anim.startRecentsActivity(recentsAnimationRunner);
1494 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(origId);
1498 }
1499 }
1500
1501 @Override
1502 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001503 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 "startActivityFromRecents()");
1505
1506 final int callingPid = Binder.getCallingPid();
1507 final int callingUid = Binder.getCallingUid();
1508 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1509 final long origId = Binder.clearCallingIdentity();
1510 try {
1511 synchronized (mGlobalLock) {
1512 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1513 safeOptions);
1514 }
1515 } finally {
1516 Binder.restoreCallingIdentity(origId);
1517 }
1518 }
1519
1520 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001521 * Public API to check if the client is allowed to start an activity on specified display.
1522 *
1523 * If the target display is private or virtual, some restrictions will apply.
1524 *
1525 * @param displayId Target display id.
1526 * @param intent Intent used to launch the activity.
1527 * @param resolvedType The MIME type of the intent.
1528 * @param userId The id of the user for whom the call is made.
1529 * @return {@code true} if a call to start an activity on the target display should succeed and
1530 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1531 */
1532 @Override
1533 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1534 String resolvedType, int userId) {
1535 final int callingUid = Binder.getCallingUid();
1536 final int callingPid = Binder.getCallingPid();
1537 final long origId = Binder.clearCallingIdentity();
1538
1539 try {
1540 // Collect information about the target of the Intent.
1541 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1542 0 /* startFlags */, null /* profilerInfo */, userId,
1543 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1544 UserHandle.USER_NULL));
1545 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1546
1547 synchronized (mGlobalLock) {
1548 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1549 aInfo);
1550 }
1551 } finally {
1552 Binder.restoreCallingIdentity(origId);
1553 }
1554 }
1555
1556 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 * This is the internal entry point for handling Activity.finish().
1558 *
1559 * @param token The Binder token referencing the Activity we want to finish.
1560 * @param resultCode Result code, if any, from this Activity.
1561 * @param resultData Result data (Intent), if any, from this Activity.
1562 * @param finishTask Whether to finish the task associated with this Activity.
1563 *
1564 * @return Returns true if the activity successfully finished, or false if it is still running.
1565 */
1566 @Override
1567 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1568 int finishTask) {
1569 // Refuse possible leaked file descriptors
1570 if (resultData != null && resultData.hasFileDescriptors()) {
1571 throw new IllegalArgumentException("File descriptors passed in Intent");
1572 }
1573
1574 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 if (r == null) {
1577 return true;
1578 }
1579 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001580 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001581 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 if (rootR == null) {
1583 Slog.w(TAG, "Finishing task with all activities already finished");
1584 }
1585 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1586 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001587 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001588 return false;
1589 }
1590
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001591 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1592 // We should consolidate.
1593 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001594 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001595 final ActivityRecord next =
1596 r.getActivityStack().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 if (next != null) {
1598 // ask watcher if this is allowed
1599 boolean resumeOK = true;
1600 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001601 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001602 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001603 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001604 Watchdog.getInstance().setActivityController(null);
1605 }
1606
1607 if (!resumeOK) {
1608 Slog.i(TAG, "Not finishing activity because controller resumed");
1609 return false;
1610 }
1611 }
1612 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001613
1614 // note down that the process has finished an activity and is in background activity
1615 // starts grace period
1616 if (r.app != null) {
1617 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1618 }
1619
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001621 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 try {
1623 boolean res;
1624 final boolean finishWithRootActivity =
1625 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1626 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1627 || (finishWithRootActivity && r == rootR)) {
1628 // If requested, remove the task that is associated to this activity only if it
1629 // was the root activity in the task. The result code and data is ignored
1630 // because we don't support returning them across task boundaries. Also, to
1631 // keep backwards compatibility we remove the task from recents when finishing
1632 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001633 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001635 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001636 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001637 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001639 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001640 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641 if (!res) {
1642 Slog.i(TAG, "Failed to finish by app-request");
1643 }
1644 }
1645 return res;
1646 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001647 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 Binder.restoreCallingIdentity(origId);
1649 }
1650 }
1651 }
1652
1653 @Override
1654 public boolean finishActivityAffinity(IBinder token) {
1655 synchronized (mGlobalLock) {
1656 final long origId = Binder.clearCallingIdentity();
1657 try {
1658 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1659 if (r == null) {
1660 return false;
1661 }
1662
1663 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1664 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001665 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001666 return false;
1667 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001668
1669 final PooledFunction p = PooledLambda.obtainFunction(
1670 ActivityRecord::finishIfSameAffinity, r,
1671 PooledLambda.__(ActivityRecord.class));
1672 r.getTask().forAllActivities(
1673 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1674 p.recycle();
1675
Andrii Kuliande93eff2019-07-12 12:21:27 -07001676 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 } finally {
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680 }
1681 }
1682
1683 @Override
1684 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1685 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001686 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001687 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001688 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001689 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1690 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001691 return;
1692 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001693 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1694 false /* processPausingActivities */, config);
1695 if (stopProfiling && r.hasProcess()) {
1696 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 }
1698 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001699 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001700 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001701 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001702 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 }
1704
1705 @Override
1706 public final void activityResumed(IBinder token) {
1707 final long origId = Binder.clearCallingIdentity();
1708 synchronized (mGlobalLock) {
1709 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001710 }
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713
1714 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001715 public final void activityTopResumedStateLost() {
1716 final long origId = Binder.clearCallingIdentity();
1717 synchronized (mGlobalLock) {
1718 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1719 }
1720 Binder.restoreCallingIdentity(origId);
1721 }
1722
1723 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 public final void activityPaused(IBinder token) {
1725 final long origId = Binder.clearCallingIdentity();
1726 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001727 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001728 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1729 if (r != null) {
1730 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001732 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734 Binder.restoreCallingIdentity(origId);
1735 }
1736
1737 @Override
1738 public final void activityStopped(IBinder token, Bundle icicle,
1739 PersistableBundle persistentState, CharSequence description) {
1740 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1741
1742 // Refuse possible leaked file descriptors
1743 if (icicle != null && icicle.hasFileDescriptors()) {
1744 throw new IllegalArgumentException("File descriptors passed in Bundle");
1745 }
1746
1747 final long origId = Binder.clearCallingIdentity();
1748
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001749 String restartingName = null;
1750 int restartingUid = 0;
1751 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001752 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001753 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001754 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001755 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001756 if (r.attachedToProcess()
1757 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1758 // The activity was requested to restart from
1759 // {@link #restartActivityProcessIfVisible}.
1760 restartingName = r.app.mName;
1761 restartingUid = r.app.mUid;
1762 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001763 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001765 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 }
1767
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001768 if (restartingName != null) {
1769 // In order to let the foreground activity can be restarted with its saved state from
1770 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1771 // until the activity reports stopped with the state. And the activity record will be
1772 // kept because the record state is restarting, then the activity will be restarted
1773 // immediately if it is still the top one.
1774 mStackSupervisor.removeRestartTimeouts(r);
1775 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1776 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001777 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778
1779 Binder.restoreCallingIdentity(origId);
1780 }
1781
1782 @Override
1783 public final void activityDestroyed(IBinder token) {
1784 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1785 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001786 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001787 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001788 try {
1789 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1790 if (activity != null) {
1791 activity.destroyed("activityDestroyed");
1792 }
1793 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001794 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001795 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001796 }
1797 }
1798 }
1799
1800 @Override
1801 public final void activityRelaunched(IBinder token) {
1802 final long origId = Binder.clearCallingIdentity();
1803 synchronized (mGlobalLock) {
1804 mStackSupervisor.activityRelaunchedLocked(token);
1805 }
1806 Binder.restoreCallingIdentity(origId);
1807 }
1808
1809 public final void activitySlept(IBinder token) {
1810 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1811
1812 final long origId = Binder.clearCallingIdentity();
1813
1814 synchronized (mGlobalLock) {
1815 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1816 if (r != null) {
1817 mStackSupervisor.activitySleptLocked(r);
1818 }
1819 }
1820
1821 Binder.restoreCallingIdentity(origId);
1822 }
1823
1824 @Override
1825 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1826 synchronized (mGlobalLock) {
1827 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1828 if (r == null) {
1829 return;
1830 }
1831 final long origId = Binder.clearCallingIdentity();
1832 try {
1833 r.setRequestedOrientation(requestedOrientation);
1834 } finally {
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837 }
1838 }
1839
1840 @Override
1841 public int getRequestedOrientation(IBinder token) {
1842 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001843 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1844 return (r != null)
1845 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001846 }
1847 }
1848
1849 @Override
1850 public void setImmersive(IBinder token, boolean immersive) {
1851 synchronized (mGlobalLock) {
1852 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1853 if (r == null) {
1854 throw new IllegalArgumentException();
1855 }
1856 r.immersive = immersive;
1857
1858 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001859 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001861 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001862 }
1863 }
1864 }
1865
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001866 void applyUpdateLockStateLocked(ActivityRecord r) {
1867 // Modifications to the UpdateLock state are done on our handler, outside
1868 // the activity manager's locks. The new state is determined based on the
1869 // state *now* of the relevant activity record. The object is passed to
1870 // the handler solely for logging detail, not to be consulted/modified.
1871 final boolean nextState = r != null && r.immersive;
1872 mH.post(() -> {
1873 if (mUpdateLock.isHeld() != nextState) {
1874 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1875 "Applying new update lock state '" + nextState + "' for " + r);
1876 if (nextState) {
1877 mUpdateLock.acquire();
1878 } else {
1879 mUpdateLock.release();
1880 }
1881 }
1882 });
1883 }
1884
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001885 @Override
1886 public boolean isImmersive(IBinder token) {
1887 synchronized (mGlobalLock) {
1888 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1889 if (r == null) {
1890 throw new IllegalArgumentException();
1891 }
1892 return r.immersive;
1893 }
1894 }
1895
1896 @Override
1897 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001900 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 return (r != null) ? r.immersive : false;
1902 }
1903 }
1904
1905 @Override
1906 public void overridePendingTransition(IBinder token, String packageName,
1907 int enterAnim, int exitAnim) {
1908 synchronized (mGlobalLock) {
1909 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1910 if (self == null) {
1911 return;
1912 }
1913
1914 final long origId = Binder.clearCallingIdentity();
1915
1916 if (self.isState(
1917 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001918 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001919 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 }
1921
1922 Binder.restoreCallingIdentity(origId);
1923 }
1924 }
1925
1926 @Override
1927 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001928 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001930 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001931 if (r == null) {
1932 return ActivityManager.COMPAT_MODE_UNKNOWN;
1933 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001934 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 }
1936 }
1937
1938 @Override
1939 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001940 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001942 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001943 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001944 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001945 if (r == null) {
1946 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1947 return;
1948 }
1949 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001950 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 }
1952 }
1953
1954 @Override
1955 public int getLaunchedFromUid(IBinder activityToken) {
1956 ActivityRecord srec;
1957 synchronized (mGlobalLock) {
1958 srec = ActivityRecord.forTokenLocked(activityToken);
1959 }
1960 if (srec == null) {
1961 return -1;
1962 }
1963 return srec.launchedFromUid;
1964 }
1965
1966 @Override
1967 public String getLaunchedFromPackage(IBinder activityToken) {
1968 ActivityRecord srec;
1969 synchronized (mGlobalLock) {
1970 srec = ActivityRecord.forTokenLocked(activityToken);
1971 }
1972 if (srec == null) {
1973 return null;
1974 }
1975 return srec.launchedFromPackage;
1976 }
1977
1978 @Override
1979 public boolean convertFromTranslucent(IBinder token) {
1980 final long origId = Binder.clearCallingIdentity();
1981 try {
1982 synchronized (mGlobalLock) {
1983 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1984 if (r == null) {
1985 return false;
1986 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001987 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 }
1989 } finally {
1990 Binder.restoreCallingIdentity(origId);
1991 }
1992 }
1993
1994 @Override
1995 public boolean convertToTranslucent(IBinder token, Bundle options) {
1996 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1997 final long origId = Binder.clearCallingIdentity();
1998 try {
1999 synchronized (mGlobalLock) {
2000 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2001 if (r == null) {
2002 return false;
2003 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002004 final ActivityRecord under = r.getTask().getActivityBelow(r);
2005 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002006 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2007 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002008 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 }
2010 } finally {
2011 Binder.restoreCallingIdentity(origId);
2012 }
2013 }
2014
2015 @Override
2016 public void notifyActivityDrawn(IBinder token) {
2017 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2018 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002019 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002020 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002021 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002022 }
2023 }
2024 }
2025
2026 @Override
2027 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2028 synchronized (mGlobalLock) {
2029 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2030 if (r == null) {
2031 return;
2032 }
2033 r.reportFullyDrawnLocked(restoredFromBundle);
2034 }
2035 }
2036
2037 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002038 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002039 synchronized (mGlobalLock) {
2040 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2041 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2042 return stack.mDisplayId;
2043 }
2044 return DEFAULT_DISPLAY;
2045 }
2046 }
2047
2048 @Override
2049 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002050 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 long ident = Binder.clearCallingIdentity();
2052 try {
2053 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002054 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 if (focusedStack != null) {
Louis Chang149d5c82019-12-30 09:47:39 +08002056 return mRootWindowContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002057 }
2058 return null;
2059 }
2060 } finally {
2061 Binder.restoreCallingIdentity(ident);
2062 }
2063 }
2064
2065 @Override
2066 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002067 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2069 final long callingId = Binder.clearCallingIdentity();
2070 try {
2071 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002072 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (stack == null) {
2074 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2075 return;
2076 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002077 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002078 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002079 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 }
2081 }
2082 } finally {
2083 Binder.restoreCallingIdentity(callingId);
2084 }
2085 }
2086
2087 @Override
2088 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002089 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2091 final long callingId = Binder.clearCallingIdentity();
2092 try {
2093 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002094 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002095 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 if (task == null) {
2097 return;
2098 }
2099 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002100 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002101 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002102 }
2103 }
2104 } finally {
2105 Binder.restoreCallingIdentity(callingId);
2106 }
2107 }
2108
2109 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002110 public void restartActivityProcessIfVisible(IBinder activityToken) {
2111 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2112 final long callingId = Binder.clearCallingIdentity();
2113 try {
2114 synchronized (mGlobalLock) {
2115 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2116 if (r == null) {
2117 return;
2118 }
2119 r.restartProcessIfVisible();
2120 }
2121 } finally {
2122 Binder.restoreCallingIdentity(callingId);
2123 }
2124 }
2125
2126 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002127 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002128 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002129 synchronized (mGlobalLock) {
2130 final long ident = Binder.clearCallingIdentity();
2131 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002132 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 "remove-task");
2134 } finally {
2135 Binder.restoreCallingIdentity(ident);
2136 }
2137 }
2138 }
2139
2140 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002141 public void removeAllVisibleRecentTasks() {
2142 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2143 synchronized (mGlobalLock) {
2144 final long ident = Binder.clearCallingIdentity();
2145 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002146 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002147 } finally {
2148 Binder.restoreCallingIdentity(ident);
2149 }
2150 }
2151 }
2152
2153 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2155 synchronized (mGlobalLock) {
2156 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2157 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002158 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002159 }
2160 }
2161 return false;
2162 }
2163
2164 @Override
2165 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2166 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002167
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002168 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002169 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2170 if (r != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002171 return r.getActivityStack().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002172 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002173 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002174 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 }
2176 }
2177
2178 /**
2179 * Attempts to move a task backwards in z-order (the order of activities within the task is
2180 * unchanged).
2181 *
2182 * There are several possible results of this call:
2183 * - if the task is locked, then we will show the lock toast
2184 * - if there is a task behind the provided task, then that task is made visible and resumed as
2185 * this task is moved to the back
2186 * - otherwise, if there are no other tasks in the stack:
2187 * - if this task is in the pinned stack, then we remove the stack completely, which will
2188 * have the effect of moving the task to the top or bottom of the fullscreen stack
2189 * (depending on whether it is visible)
2190 * - otherwise, we simply return home and hide this task
2191 *
2192 * @param token A reference to the activity we wish to move
2193 * @param nonRoot If false then this only works if the activity is the root
2194 * of a task; if true it will work for any activity in a task.
2195 * @return Returns true if the move completed, false if not.
2196 */
2197 @Override
2198 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002199 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002200 synchronized (mGlobalLock) {
2201 final long origId = Binder.clearCallingIdentity();
2202 try {
2203 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002204 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002205 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002206 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207 }
2208 } finally {
2209 Binder.restoreCallingIdentity(origId);
2210 }
2211 }
2212 return false;
2213 }
2214
2215 @Override
2216 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002217 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 long ident = Binder.clearCallingIdentity();
2219 Rect rect = new Rect();
2220 try {
2221 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002222 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2224 if (task == null) {
2225 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2226 return rect;
2227 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002228 if (task.getParent() != null) {
2229 rect.set(task.getBounds());
2230 } else if (task.mLastNonFullscreenBounds != null) {
2231 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 }
2233 }
2234 } finally {
2235 Binder.restoreCallingIdentity(ident);
2236 }
2237 return rect;
2238 }
2239
2240 @Override
2241 public ActivityManager.TaskDescription getTaskDescription(int id) {
2242 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002245 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2247 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002248 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 }
2250 }
2251 return null;
2252 }
2253
2254 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002255 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2256 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2257 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2258 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2259 return;
2260 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002261 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 synchronized (mGlobalLock) {
2263 final long ident = Binder.clearCallingIdentity();
2264 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002265 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002266 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 if (task == null) {
2268 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2269 return;
2270 }
2271
2272 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2273 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2274
2275 if (!task.isActivityTypeStandardOrUndefined()) {
2276 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2277 + " non-standard task " + taskId + " to windowing mode="
2278 + windowingMode);
2279 }
2280
2281 final ActivityStack stack = task.getStack();
2282 if (toTop) {
2283 stack.moveToFront("setTaskWindowingMode", task);
2284 }
2285 stack.setWindowingMode(windowingMode);
2286 } finally {
2287 Binder.restoreCallingIdentity(ident);
2288 }
2289 }
2290 }
2291
2292 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002293 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002294 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 ActivityRecord r = getCallingRecordLocked(token);
2296 return r != null ? r.info.packageName : null;
2297 }
2298 }
2299
2300 @Override
2301 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002302 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002303 ActivityRecord r = getCallingRecordLocked(token);
2304 return r != null ? r.intent.getComponent() : null;
2305 }
2306 }
2307
2308 private ActivityRecord getCallingRecordLocked(IBinder token) {
2309 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2310 if (r == null) {
2311 return null;
2312 }
2313 return r.resultTo;
2314 }
2315
2316 @Override
2317 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319
2320 synchronized (mGlobalLock) {
2321 final long origId = Binder.clearCallingIdentity();
2322 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002323 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002324 } finally {
2325 Binder.restoreCallingIdentity(origId);
2326 }
2327 }
2328 }
2329
Mark Renouf446251d2019-04-26 10:22:41 -04002330 @Override
2331 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2332 synchronized (mGlobalLock) {
2333 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2334 if (r == null) {
2335 return;
2336 }
2337 ActivityStack stack = r.getActivityStack();
2338 if (stack != null && stack.isSingleTaskInstance()) {
2339 // Single-task stacks are used for activities which are presented in floating
2340 // windows above full screen activities. Instead of directly finishing the
2341 // task, a task change listener is used to notify SystemUI so the action can be
2342 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002343 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002344 mTaskChangeNotificationController
2345 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2346 } else {
2347 try {
2348 callback.requestFinish();
2349 } catch (RemoteException e) {
2350 Slog.e(TAG, "Failed to invoke request finish callback", e);
2351 }
2352 }
2353 }
2354 }
2355
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 /**
2357 * TODO: Add mController hook
2358 */
2359 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2361 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002362 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363
2364 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2365 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2367 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 }
2369 }
2370
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2372 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 final int callingPid = Binder.getCallingPid();
2376 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002377 if (!isSameApp(callingUid, callingPackage)) {
2378 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2379 + Binder.getCallingPid() + " as package " + callingPackage;
2380 Slog.w(TAG, msg);
2381 throw new SecurityException(msg);
2382 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002383 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 SafeActivityOptions.abort(options);
2385 return;
2386 }
2387 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 WindowProcessController callerApp = null;
2389 if (appThread != null) {
2390 callerApp = getProcessController(appThread);
2391 }
2392 final ActivityStarter starter = getActivityStartController().obtainStarter(
2393 null /* intent */, "moveTaskToFront");
2394 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2395 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002396 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002397 return;
2398 }
2399 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002400 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002401 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 if (task == null) {
2403 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002404 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002405 return;
2406 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002407 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002408 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002409 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 return;
2411 }
2412 ActivityOptions realOptions = options != null
2413 ? options.getOptions(mStackSupervisor)
2414 : null;
2415 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2416 false /* forceNonResizable */);
2417
Wale Ogunwale21e06482019-11-18 05:14:15 -08002418 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002419 if (topActivity != null) {
2420
2421 // We are reshowing a task, use a starting window to hide the initial draw delay
2422 // so the transition can start earlier.
2423 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2424 true /* taskSwitch */, fromRecents);
2425 }
2426 } finally {
2427 Binder.restoreCallingIdentity(origId);
2428 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002429 }
2430
Ricky Waiaca8a772019-04-04 16:01:06 +01002431 /**
2432 * Return true if callingUid is system, or packageName belongs to that callingUid.
2433 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002434 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002435 try {
2436 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2437 if (packageName == null) {
2438 return false;
2439 }
2440 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2441 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2442 UserHandle.getUserId(callingUid));
2443 return UserHandle.isSameApp(callingUid, uid);
2444 }
2445 } catch (RemoteException e) {
2446 // Should not happen
2447 }
2448 return true;
2449 }
2450
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002451 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2452 int callingPid, int callingUid, String name) {
2453 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2454 return true;
2455 }
2456
2457 if (getRecentTasks().isCallerRecents(sourceUid)) {
2458 return true;
2459 }
2460
2461 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2462 if (perm == PackageManager.PERMISSION_GRANTED) {
2463 return true;
2464 }
2465 if (checkAllowAppSwitchUid(sourceUid)) {
2466 return true;
2467 }
2468
2469 // If the actual IPC caller is different from the logical source, then
2470 // also see if they are allowed to control app switches.
2471 if (callingUid != -1 && callingUid != sourceUid) {
2472 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2473 if (perm == PackageManager.PERMISSION_GRANTED) {
2474 return true;
2475 }
2476 if (checkAllowAppSwitchUid(callingUid)) {
2477 return true;
2478 }
2479 }
2480
2481 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2482 return false;
2483 }
2484
2485 private boolean checkAllowAppSwitchUid(int uid) {
2486 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2487 if (types != null) {
2488 for (int i = types.size() - 1; i >= 0; i--) {
2489 if (types.valueAt(i).intValue() == uid) {
2490 return true;
2491 }
2492 }
2493 }
2494 return false;
2495 }
2496
2497 @Override
2498 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2499 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2500 "setActivityController()");
2501 synchronized (mGlobalLock) {
2502 mController = controller;
2503 mControllerIsAMonkey = imAMonkey;
2504 Watchdog.getInstance().setActivityController(controller);
2505 }
2506 }
2507
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002508 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002509 synchronized (mGlobalLock) {
2510 return mController != null && mControllerIsAMonkey;
2511 }
2512 }
2513
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002514 @Override
2515 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2516 synchronized (mGlobalLock) {
2517 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2518 }
2519 }
2520
2521 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002522 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2523 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2524 }
2525
2526 @Override
2527 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2528 @WindowConfiguration.ActivityType int ignoreActivityType,
2529 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2530 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002531 final int callingPid = Binder.getCallingPid();
2532 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002533 final int[] profileIds = getUserManager().getProfileIds(
2534 UserHandle.getUserId(callingUid), true);
2535 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2536 for (int i = 0; i < profileIds.length; i++) {
2537 callingProfileIds.add(profileIds[i]);
2538 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2540
2541 synchronized (mGlobalLock) {
2542 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2543
Nicholas Sauer0259e532019-08-30 08:24:55 -07002544 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002545 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002546 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002547 }
2548
2549 return list;
2550 }
2551
2552 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002553 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2554 synchronized (mGlobalLock) {
2555 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002556 try {
2557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2558 if (r == null) return;
2559
2560 final PooledConsumer c = PooledLambda.obtainConsumer(
2561 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2562 r, resultWho, requestCode);
2563 // TODO: This should probably only loop over the task since you need to be in the
2564 // same task to return results.
2565 r.getActivityStack().forAllActivities(c);
2566 c.recycle();
2567
2568 updateOomAdj();
2569 } finally {
2570 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002571 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002572 }
2573 }
2574
2575 @Override
2576 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002577 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002578 ActivityStack stack = ActivityRecord.getStackLocked(token);
2579 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002580 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002581 }
2582 return false;
2583 }
2584 }
2585
2586 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002587 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002589 synchronized (mGlobalLock) {
2590 final long ident = Binder.clearCallingIdentity();
2591 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002592 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002593 if (task == null) {
2594 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2595 return;
2596 }
2597
2598 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2599 + " to stackId=" + stackId + " toTop=" + toTop);
2600
Louis Chang149d5c82019-12-30 09:47:39 +08002601 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002602 if (stack == null) {
2603 throw new IllegalStateException(
2604 "moveTaskToStack: No stack for stackId=" + stackId);
2605 }
2606 if (!stack.isActivityTypeStandardOrUndefined()) {
2607 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2608 + taskId + " to stack " + stackId);
2609 }
2610 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002611 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002612 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2613 }
2614 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2615 "moveTaskToStack");
2616 } finally {
2617 Binder.restoreCallingIdentity(ident);
2618 }
2619 }
2620 }
2621
2622 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002623 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2624 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002625
2626 final long ident = Binder.clearCallingIdentity();
2627 try {
2628 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002629 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002630 if (stack == null) {
2631 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2632 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002633 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002634 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2635 throw new IllegalArgumentException("Stack: " + stackId
2636 + " doesn't support animated resize.");
2637 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002638 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002639 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002640 }
2641 } finally {
2642 Binder.restoreCallingIdentity(ident);
2643 }
2644 }
2645
wilsonshih5c4cf522019-01-25 09:03:47 +08002646 @Override
2647 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2648 int animationDuration) {
2649 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2650
2651 final long ident = Binder.clearCallingIdentity();
2652 try {
2653 synchronized (mGlobalLock) {
2654 if (xOffset == 0 && yOffset == 0) {
2655 return;
2656 }
Louis Chang149d5c82019-12-30 09:47:39 +08002657 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002658 if (stack == null) {
2659 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2660 return;
2661 }
2662 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2663 throw new IllegalArgumentException("Stack: " + stackId
2664 + " doesn't support animated resize.");
2665 }
2666 final Rect destBounds = new Rect();
2667 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002668 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002669 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2670 return;
2671 }
2672 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002673 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002674 animationDuration, false /* fromFullscreen */);
2675 }
2676 } finally {
2677 Binder.restoreCallingIdentity(ident);
2678 }
2679 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 /**
2681 * Moves the specified task to the primary-split-screen stack.
2682 *
2683 * @param taskId Id of task to move.
2684 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2685 * exist already. See
2686 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2687 * and
2688 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2689 * @param toTop If the task and stack should be moved to the top.
2690 * @param animate Whether we should play an animation for the moving the task.
2691 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2692 * stack. Pass {@code null} to use default bounds.
2693 * @param showRecents If the recents activity should be shown on the other side of the task
2694 * going into split-screen mode.
2695 */
2696 @Override
2697 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2698 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002699 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002700 "setTaskWindowingModeSplitScreenPrimary()");
2701 synchronized (mGlobalLock) {
2702 final long ident = Binder.clearCallingIdentity();
2703 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002704 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002705 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 if (task == null) {
2707 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2708 return false;
2709 }
2710 if (DEBUG_STACK) Slog.d(TAG_STACK,
2711 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2712 + " to createMode=" + createMode + " toTop=" + toTop);
2713 if (!task.isActivityTypeStandardOrUndefined()) {
2714 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2715 + " non-standard task " + taskId + " to split-screen windowing mode");
2716 }
2717
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002718 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 final int windowingMode = task.getWindowingMode();
2720 final ActivityStack stack = task.getStack();
2721 if (toTop) {
2722 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2723 }
2724 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002725 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2726 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 return windowingMode != task.getWindowingMode();
2728 } finally {
2729 Binder.restoreCallingIdentity(ident);
2730 }
2731 }
2732 }
2733
2734 /**
2735 * Removes stacks in the input windowing modes from the system if they are of activity type
2736 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2737 */
2738 @Override
2739 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002741 "removeStacksInWindowingModes()");
2742
2743 synchronized (mGlobalLock) {
2744 final long ident = Binder.clearCallingIdentity();
2745 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002746 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002747 } finally {
2748 Binder.restoreCallingIdentity(ident);
2749 }
2750 }
2751 }
2752
2753 @Override
2754 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002755 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002756 "removeStacksWithActivityTypes()");
2757
2758 synchronized (mGlobalLock) {
2759 final long ident = Binder.clearCallingIdentity();
2760 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002761 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002762 } finally {
2763 Binder.restoreCallingIdentity(ident);
2764 }
2765 }
2766 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767
2768 @Override
2769 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2770 int userId) {
2771 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002772 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2773 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 final boolean detailed = checkGetTasksPermission(
2776 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2777 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 == PackageManager.PERMISSION_GRANTED;
2779
2780 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002781 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 callingUid);
2783 }
2784 }
2785
2786 @Override
2787 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 long ident = Binder.clearCallingIdentity();
2790 try {
2791 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002792 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 }
2794 } finally {
2795 Binder.restoreCallingIdentity(ident);
2796 }
2797 }
2798
2799 @Override
2800 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002801 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 long ident = Binder.clearCallingIdentity();
2803 try {
2804 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002805 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 }
2807 } finally {
2808 Binder.restoreCallingIdentity(ident);
2809 }
2810 }
2811
2812 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002813 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2814 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2815 long ident = Binder.clearCallingIdentity();
2816 try {
2817 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002818 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002819 }
2820 } finally {
2821 Binder.restoreCallingIdentity(ident);
2822 }
2823 }
2824
2825 @Override
2826 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2827 int displayId) {
2828 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2829 long ident = Binder.clearCallingIdentity();
2830 try {
2831 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002832 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002833 }
2834 } finally {
2835 Binder.restoreCallingIdentity(ident);
2836 }
2837 }
2838
2839 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002840 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002841 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 final long callingUid = Binder.getCallingUid();
2843 final long origId = Binder.clearCallingIdentity();
2844 try {
2845 synchronized (mGlobalLock) {
2846 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002847 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2849 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2850 }
2851 } finally {
2852 Binder.restoreCallingIdentity(origId);
2853 }
2854 }
2855
2856 @Override
2857 public void startLockTaskModeByToken(IBinder token) {
2858 synchronized (mGlobalLock) {
2859 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2860 if (r == null) {
2861 return;
2862 }
Louis Changcdec0802019-11-11 11:45:07 +08002863 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 }
2865 }
2866
2867 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002868 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002869 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870 // This makes inner call to look as if it was initiated by system.
2871 long ident = Binder.clearCallingIdentity();
2872 try {
2873 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002874 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002875 MATCH_TASK_IN_STACKS_ONLY);
2876 if (task == null) {
2877 return;
2878 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879
2880 // When starting lock task mode the stack must be in front and focused
2881 task.getStack().moveToFront("startSystemLockTaskMode");
2882 startLockTaskModeLocked(task, true /* isSystemCaller */);
2883 }
2884 } finally {
2885 Binder.restoreCallingIdentity(ident);
2886 }
2887 }
2888
2889 @Override
2890 public void stopLockTaskModeByToken(IBinder token) {
2891 synchronized (mGlobalLock) {
2892 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2893 if (r == null) {
2894 return;
2895 }
Louis Changcdec0802019-11-11 11:45:07 +08002896 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 }
2898 }
2899
2900 /**
2901 * This API should be called by SystemUI only when user perform certain action to dismiss
2902 * lock task mode. We should only dismiss pinned lock task mode in this case.
2903 */
2904 @Override
2905 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002906 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002907 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2908 }
2909
Louis Changcdec0802019-11-11 11:45:07 +08002910 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2912 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2913 return;
2914 }
2915
Louis Chang149d5c82019-12-30 09:47:39 +08002916 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002917 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 throw new IllegalArgumentException("Invalid task, not in foreground");
2919 }
2920
2921 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2922 // system or a specific app.
2923 // * System-initiated requests will only start the pinned mode (screen pinning)
2924 // * App-initiated requests
2925 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2926 // - will start the pinned mode, otherwise
2927 final int callingUid = Binder.getCallingUid();
2928 long ident = Binder.clearCallingIdentity();
2929 try {
2930 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08002931 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002932
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002933 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934 } finally {
2935 Binder.restoreCallingIdentity(ident);
2936 }
2937 }
2938
Louis Changcdec0802019-11-11 11:45:07 +08002939 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 final int callingUid = Binder.getCallingUid();
2941 long ident = Binder.clearCallingIdentity();
2942 try {
2943 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002944 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 }
2946 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2947 // task and jumping straight into a call in the case of emergency call back.
2948 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2949 if (tm != null) {
2950 tm.showInCallScreen(false);
2951 }
2952 } finally {
2953 Binder.restoreCallingIdentity(ident);
2954 }
2955 }
2956
2957 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002958 public void updateLockTaskPackages(int userId, String[] packages) {
2959 final int callingUid = Binder.getCallingUid();
2960 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2961 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2962 "updateLockTaskPackages()");
2963 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002964 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002965 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2966 + Arrays.toString(packages));
2967 getLockTaskController().updateLockTaskPackages(userId, packages);
2968 }
2969 }
2970
2971 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 public boolean isInLockTaskMode() {
2973 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2974 }
2975
2976 @Override
2977 public int getLockTaskModeState() {
2978 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002979 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 }
2981 }
2982
2983 @Override
2984 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2985 synchronized (mGlobalLock) {
2986 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2987 if (r != null) {
2988 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08002989 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002991 }
2992 }
2993 }
2994
2995 @Override
2996 public Bundle getActivityOptions(IBinder token) {
2997 final long origId = Binder.clearCallingIdentity();
2998 try {
2999 synchronized (mGlobalLock) {
3000 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3001 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003002 final ActivityOptions activityOptions = r.takeOptionsLocked(
3003 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 return activityOptions == null ? null : activityOptions.toBundle();
3005 }
3006 return null;
3007 }
3008 } finally {
3009 Binder.restoreCallingIdentity(origId);
3010 }
3011 }
3012
3013 @Override
3014 public List<IBinder> getAppTasks(String callingPackage) {
3015 int callingUid = Binder.getCallingUid();
3016 long ident = Binder.clearCallingIdentity();
3017 try {
3018 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003019 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 }
3021 } finally {
3022 Binder.restoreCallingIdentity(ident);
3023 }
3024 }
3025
3026 @Override
3027 public void finishVoiceTask(IVoiceInteractionSession session) {
3028 synchronized (mGlobalLock) {
3029 final long origId = Binder.clearCallingIdentity();
3030 try {
3031 // TODO: VI Consider treating local voice interactions and voice tasks
3032 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003033 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 } finally {
3035 Binder.restoreCallingIdentity(origId);
3036 }
3037 }
3038
3039 }
3040
3041 @Override
3042 public boolean isTopOfTask(IBinder token) {
3043 synchronized (mGlobalLock) {
3044 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003045 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 }
3047 }
3048
3049 @Override
3050 public void notifyLaunchTaskBehindComplete(IBinder token) {
3051 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3052 }
3053
3054 @Override
3055 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003056 mH.post(() -> {
3057 synchronized (mGlobalLock) {
3058 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003059 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003060 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003061 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003062 } catch (RemoteException e) {
3063 }
3064 }
3065 }
3066
3067 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 }
3069
3070 /** Called from an app when assist data is ready. */
3071 @Override
3072 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3073 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003075 synchronized (pae) {
3076 pae.result = extras;
3077 pae.structure = structure;
3078 pae.content = content;
3079 if (referrer != null) {
3080 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3081 }
3082 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003083 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003084 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003085 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003086 structure.setHomeActivity(pae.isHome);
3087 }
3088 pae.haveResult = true;
3089 pae.notifyAll();
3090 if (pae.intent == null && pae.receiver == null) {
3091 // Caller is just waiting for the result.
3092 return;
3093 }
3094 }
3095 // We are now ready to launch the assist activity.
3096 IAssistDataReceiver sendReceiver = null;
3097 Bundle sendBundle = null;
3098 synchronized (mGlobalLock) {
3099 buildAssistBundleLocked(pae, extras);
3100 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003101 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003102 if (!exists) {
3103 // Timed out.
3104 return;
3105 }
3106
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003107 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003108 // Caller wants result sent back to them.
3109 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003110 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003111 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003112 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3113 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003114 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3115 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3116 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3117 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3118 }
3119 }
3120 if (sendReceiver != null) {
3121 try {
3122 sendReceiver.onHandleAssistData(sendBundle);
3123 } catch (RemoteException e) {
3124 }
3125 return;
3126 }
3127
3128 final long ident = Binder.clearCallingIdentity();
3129 try {
3130 if (TextUtils.equals(pae.intent.getAction(),
3131 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003132 // Start voice interaction through VoiceInteractionManagerService.
3133 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3134 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 } else {
3136 pae.intent.replaceExtras(pae.extras);
3137 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3138 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3139 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003140 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141
3142 try {
3143 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3144 } catch (ActivityNotFoundException e) {
3145 Slog.w(TAG, "No activity to handle assist action.", e);
3146 }
3147 }
3148 } finally {
3149 Binder.restoreCallingIdentity(ident);
3150 }
3151 }
3152
3153 @Override
3154 public int addAppTask(IBinder activityToken, Intent intent,
3155 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3156 final int callingUid = Binder.getCallingUid();
3157 final long callingIdent = Binder.clearCallingIdentity();
3158
3159 try {
3160 synchronized (mGlobalLock) {
3161 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3162 if (r == null) {
3163 throw new IllegalArgumentException("Activity does not exist; token="
3164 + activityToken);
3165 }
3166 ComponentName comp = intent.getComponent();
3167 if (comp == null) {
3168 throw new IllegalArgumentException("Intent " + intent
3169 + " must specify explicit component");
3170 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003171 if (thumbnail.getWidth() != mThumbnailWidth
3172 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 throw new IllegalArgumentException("Bad thumbnail size: got "
3174 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003175 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003176 }
3177 if (intent.getSelector() != null) {
3178 intent.setSelector(null);
3179 }
3180 if (intent.getSourceBounds() != null) {
3181 intent.setSourceBounds(null);
3182 }
3183 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3184 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3185 // The caller has added this as an auto-remove task... that makes no
3186 // sense, so turn off auto-remove.
3187 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3188 }
3189 }
3190 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3191 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3192 if (ainfo.applicationInfo.uid != callingUid) {
3193 throw new SecurityException(
3194 "Can't add task for another application: target uid="
3195 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3196 }
3197
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003198 final ActivityStack stack = r.getActivityStack();
Louis Changcdec0802019-11-11 11:45:07 +08003199 final Task task = stack.createTask(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003200 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003202 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003203 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003204 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 return INVALID_TASK_ID;
3206 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003207 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208
3209 // TODO: Send the thumbnail to WM to store it.
3210
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003211 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003212 }
3213 } finally {
3214 Binder.restoreCallingIdentity(callingIdent);
3215 }
3216 }
3217
3218 @Override
3219 public Point getAppTaskThumbnailSize() {
3220 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003221 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 }
3223 }
3224
3225 @Override
3226 public void setTaskResizeable(int taskId, int resizeableMode) {
3227 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003228 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003229 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3230 if (task == null) {
3231 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3232 return;
3233 }
3234 task.setResizeMode(resizeableMode);
3235 }
3236 }
3237
3238 @Override
3239 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003240 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 long ident = Binder.clearCallingIdentity();
3242 try {
3243 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003244 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003245 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 if (task == null) {
3247 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3248 return;
3249 }
3250 // Place the task in the right stack if it isn't there already based on
3251 // the requested bounds.
3252 // The stack transition logic is:
3253 // - a null bounds on a freeform task moves that task to fullscreen
3254 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3255 // that task to freeform
3256 // - otherwise the task is not moved
3257 ActivityStack stack = task.getStack();
3258 if (!task.getWindowConfiguration().canResizeTask()) {
3259 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3260 }
3261 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3262 stack = stack.getDisplay().getOrCreateStack(
3263 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3264 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3265 stack = stack.getDisplay().getOrCreateStack(
3266 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3267 }
3268
3269 // Reparent the task to the right stack if necessary
3270 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3271 if (stack != task.getStack()) {
3272 // Defer resume until the task is resized below
3273 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3274 DEFER_RESUME, "resizeTask");
3275 preserveWindow = false;
3276 }
3277
3278 // After reparenting (which only resizes the task to the stack bounds), resize the
3279 // task to the actual bounds provided
3280 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3281 }
3282 } finally {
3283 Binder.restoreCallingIdentity(ident);
3284 }
3285 }
3286
Evan Roskyddedfd42019-10-04 13:38:38 -07003287 private void sanitizeAndApplyConfigChange(ConfigurationContainer container,
3288 WindowContainerTransaction.Change change) {
Evan Rosky282ee672019-11-13 15:50:46 -08003289 if (!(container instanceof Task || container instanceof ActivityStack)) {
Evan Roskyddedfd42019-10-04 13:38:38 -07003290 throw new RuntimeException("Invalid token in task transaction");
3291 }
3292 // The "client"-facing API should prevent bad changes; however, just in case, sanitize
3293 // masks here.
3294 int configMask = change.getConfigSetMask();
3295 int windowMask = change.getWindowSetMask();
3296 configMask &= ActivityInfo.CONFIG_WINDOW_CONFIGURATION
3297 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
3298 windowMask &= WindowConfiguration.WINDOW_CONFIG_BOUNDS;
3299 Configuration c = new Configuration(container.getRequestedOverrideConfiguration());
3300 c.setTo(change.getConfiguration(), configMask, windowMask);
3301 container.onRequestedOverrideConfigurationChanged(c);
Hongwei Wangebf18082019-09-26 14:25:11 -07003302 // TODO(b/145675353): remove the following once we could apply new bounds to the
3303 // pinned stack together with its children.
3304 resizePinnedStackIfNeeded(container, configMask, windowMask, c);
3305 }
3306
3307 private void resizePinnedStackIfNeeded(ConfigurationContainer container, int configMask,
3308 int windowMask, Configuration config) {
3309 if ((container instanceof ActivityStack)
3310 && ((configMask & ActivityInfo.CONFIG_WINDOW_CONFIGURATION) != 0)
3311 && ((windowMask & WindowConfiguration.WINDOW_CONFIG_BOUNDS) != 0)) {
3312 final ActivityStack stack = (ActivityStack) container;
3313 if (stack.inPinnedWindowingMode()) {
3314 stack.resize(config.windowConfiguration.getBounds(),
3315 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
3316 PRESERVE_WINDOWS, true /* deferResume */);
3317 }
3318 }
Evan Roskyddedfd42019-10-04 13:38:38 -07003319 }
3320
3321 @Override
3322 public void applyContainerTransaction(WindowContainerTransaction t) {
3323 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "applyContainerTransaction()");
3324 long ident = Binder.clearCallingIdentity();
3325 try {
3326 if (t == null) {
3327 return;
3328 }
3329 synchronized (mGlobalLock) {
3330 Iterator<Map.Entry<IBinder, WindowContainerTransaction.Change>> entries =
3331 t.getChanges().entrySet().iterator();
3332 while (entries.hasNext()) {
3333 final Map.Entry<IBinder, WindowContainerTransaction.Change> entry =
3334 entries.next();
3335 final ConfigurationContainer cc = ConfigurationContainer.RemoteToken.fromBinder(
3336 entry.getKey()).getContainer();
3337 sanitizeAndApplyConfigChange(cc, entry.getValue());
3338 }
3339 }
3340 } finally {
3341 Binder.restoreCallingIdentity(ident);
3342 }
3343 }
3344
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003345 @Override
3346 public boolean releaseActivityInstance(IBinder token) {
3347 synchronized (mGlobalLock) {
3348 final long origId = Binder.clearCallingIdentity();
3349 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003350 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3351 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 return false;
3353 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003354 r.destroyImmediately(true /* removeFromApp */, "app-req");
3355 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 } finally {
3357 Binder.restoreCallingIdentity(origId);
3358 }
3359 }
3360 }
3361
3362 @Override
3363 public void releaseSomeActivities(IApplicationThread appInt) {
3364 synchronized (mGlobalLock) {
3365 final long origId = Binder.clearCallingIdentity();
3366 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003367 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003368 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 } finally {
3370 Binder.restoreCallingIdentity(origId);
3371 }
3372 }
3373 }
3374
3375 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003376 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003377 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 != PackageManager.PERMISSION_GRANTED) {
3379 throw new SecurityException("Requires permission "
3380 + android.Manifest.permission.DEVICE_POWER);
3381 }
3382
3383 synchronized (mGlobalLock) {
3384 long ident = Binder.clearCallingIdentity();
3385 if (mKeyguardShown != keyguardShowing) {
3386 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003387 final Message msg = PooledLambda.obtainMessage(
3388 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3389 keyguardShowing);
3390 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 }
3392 try {
wilsonshih177261f2019-02-22 12:02:18 +08003393 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 } finally {
3395 Binder.restoreCallingIdentity(ident);
3396 }
3397 }
3398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003399 mH.post(() -> {
3400 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3401 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3402 }
3403 });
3404 }
3405
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003406 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003407 mH.post(() -> {
3408 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3409 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3410 }
3411 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 }
3413
3414 @Override
3415 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003416 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3417 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418
3419 final File passedIconFile = new File(filePath);
3420 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3421 passedIconFile.getName());
3422 if (!legitIconFile.getPath().equals(filePath)
3423 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3424 throw new IllegalArgumentException("Bad file path: " + filePath
3425 + " passed for userId " + userId);
3426 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003427 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 }
3429
3430 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003431 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 synchronized (mGlobalLock) {
3434 final long ident = Binder.clearCallingIdentity();
3435 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003436 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 if (stack == null) {
3438 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3439 return;
3440 }
3441 if (!stack.isActivityTypeStandardOrUndefined()) {
3442 throw new IllegalArgumentException(
3443 "Removing non-standard stack is not allowed.");
3444 }
3445 mStackSupervisor.removeStack(stack);
3446 } finally {
3447 Binder.restoreCallingIdentity(ident);
3448 }
3449 }
3450 }
3451
3452 @Override
3453 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003454 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455
3456 synchronized (mGlobalLock) {
3457 final long ident = Binder.clearCallingIdentity();
3458 try {
3459 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3460 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003461 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003462 } finally {
3463 Binder.restoreCallingIdentity(ident);
3464 }
3465 }
3466 }
3467
3468 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003469 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003470 synchronized (mGlobalLock) {
3471 long ident = Binder.clearCallingIdentity();
3472 try {
3473 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3474 if (r == null) {
3475 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003476 "toggleFreeformWindowingMode: No activity record matching token="
3477 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 }
3479
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003480 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003481 if (stack == null) {
3482 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3483 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
Yunfan Chend967af82019-01-17 18:30:18 +09003486 if (!stack.inFreeformWindowingMode()
3487 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3488 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3489 + "toggle between fullscreen and freeform.");
3490 }
3491
3492 if (stack.inFreeformWindowingMode()) {
3493 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003494 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003495 throw new IllegalStateException("Size-compat windows are currently not"
3496 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003497 } else if (stack.getParent().inFreeformWindowingMode()) {
3498 // If the window is on a freeform display, set it to undefined. It will be
3499 // resolved to freeform and it can adjust windowing mode when the display mode
3500 // changes in runtime.
3501 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003502 } else {
3503 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3504 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 } finally {
3506 Binder.restoreCallingIdentity(ident);
3507 }
3508 }
3509 }
3510
3511 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3512 @Override
3513 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003514 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003515 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003516 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 }
3518
3519 /** Unregister a task stack listener so that it stops receiving callbacks. */
3520 @Override
3521 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003522 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003523 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003524 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003525 }
3526
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003527 @Override
3528 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3529 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3530 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3531 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3532 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3533 }
3534
3535 @Override
3536 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3537 IBinder activityToken, int flags) {
3538 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3539 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3540 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3541 }
3542
3543 @Override
3544 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3545 Bundle args) {
3546 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3547 true /* focused */, true /* newSessionId */, userHandle, args,
3548 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3549 }
3550
3551 @Override
3552 public Bundle getAssistContextExtras(int requestType) {
3553 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3554 null, null, true /* focused */, true /* newSessionId */,
3555 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3556 if (pae == null) {
3557 return null;
3558 }
3559 synchronized (pae) {
3560 while (!pae.haveResult) {
3561 try {
3562 pae.wait();
3563 } catch (InterruptedException e) {
3564 }
3565 }
3566 }
3567 synchronized (mGlobalLock) {
3568 buildAssistBundleLocked(pae, pae.result);
3569 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003570 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003571 }
3572 return pae.extras;
3573 }
3574
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003575 /**
3576 * Binder IPC calls go through the public entry point.
3577 * This can be called with or without the global lock held.
3578 */
3579 private static int checkCallingPermission(String permission) {
3580 return checkPermission(
3581 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3582 }
3583
3584 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003585 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003586 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3587 mAmInternal.enforceCallingPermission(permission, func);
3588 }
3589 }
3590
3591 @VisibleForTesting
3592 int checkGetTasksPermission(String permission, int pid, int uid) {
3593 return checkPermission(permission, pid, uid);
3594 }
3595
3596 static int checkPermission(String permission, int pid, int uid) {
3597 if (permission == null) {
3598 return PackageManager.PERMISSION_DENIED;
3599 }
3600 return checkComponentPermission(permission, pid, uid, -1, true);
3601 }
3602
Wale Ogunwale214f3482018-10-04 11:00:47 -07003603 public static int checkComponentPermission(String permission, int pid, int uid,
3604 int owningUid, boolean exported) {
3605 return ActivityManagerService.checkComponentPermission(
3606 permission, pid, uid, owningUid, exported);
3607 }
3608
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003609 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3610 if (getRecentTasks().isCallerRecents(callingUid)) {
3611 // Always allow the recents component to get tasks
3612 return true;
3613 }
3614
3615 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3616 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3617 if (!allowed) {
3618 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3619 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3620 // Temporary compatibility: some existing apps on the system image may
3621 // still be requesting the old permission and not switched to the new
3622 // one; if so, we'll still allow them full access. This means we need
3623 // to see if they are holding the old permission and are a system app.
3624 try {
3625 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3626 allowed = true;
3627 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3628 + " is using old GET_TASKS but privileged; allowing");
3629 }
3630 } catch (RemoteException e) {
3631 }
3632 }
3633 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3634 + " does not hold REAL_GET_TASKS; limiting output");
3635 }
3636 return allowed;
3637 }
3638
Nicholas Sauer0259e532019-08-30 08:24:55 -07003639 boolean isCrossUserAllowed(int pid, int uid) {
3640 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3641 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3642 }
3643
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3645 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3646 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3647 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003648 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 "enqueueAssistContext()");
3650
3651 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003652 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003653 if (activity == null) {
3654 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3655 return null;
3656 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003657 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3659 return null;
3660 }
3661 if (focused) {
3662 if (activityToken != null) {
3663 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3664 if (activity != caller) {
3665 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3666 + " is not current top " + activity);
3667 return null;
3668 }
3669 }
3670 } else {
3671 activity = ActivityRecord.forTokenLocked(activityToken);
3672 if (activity == null) {
3673 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3674 + " couldn't be found");
3675 return null;
3676 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003677 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003678 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3679 return null;
3680 }
3681 }
3682
3683 PendingAssistExtras pae;
3684 Bundle extras = new Bundle();
3685 if (args != null) {
3686 extras.putAll(args);
3687 }
3688 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003689 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003690
3691 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3692 userHandle);
3693 pae.isHome = activity.isActivityTypeHome();
3694
3695 // Increment the sessionId if necessary
3696 if (newSessionId) {
3697 mViSessionId++;
3698 }
3699 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003700 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3701 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003702 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003703 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003704 } catch (RemoteException e) {
3705 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3706 return null;
3707 }
3708 return pae;
3709 }
3710 }
3711
3712 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3713 if (result != null) {
3714 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3715 }
3716 if (pae.hint != null) {
3717 pae.extras.putBoolean(pae.hint, true);
3718 }
3719 }
3720
3721 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3722 IAssistDataReceiver receiver;
3723 synchronized (mGlobalLock) {
3724 mPendingAssistExtras.remove(pae);
3725 receiver = pae.receiver;
3726 }
3727 if (receiver != null) {
3728 // Caller wants result sent back to them.
3729 Bundle sendBundle = new Bundle();
3730 // At least return the receiver extras
3731 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3732 try {
3733 pae.receiver.onHandleAssistData(sendBundle);
3734 } catch (RemoteException e) {
3735 }
3736 }
3737 }
3738
3739 public class PendingAssistExtras extends Binder implements Runnable {
3740 public final ActivityRecord activity;
3741 public boolean isHome;
3742 public final Bundle extras;
3743 public final Intent intent;
3744 public final String hint;
3745 public final IAssistDataReceiver receiver;
3746 public final int userHandle;
3747 public boolean haveResult = false;
3748 public Bundle result = null;
3749 public AssistStructure structure = null;
3750 public AssistContent content = null;
3751 public Bundle receiverExtras;
3752
3753 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3754 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3755 int _userHandle) {
3756 activity = _activity;
3757 extras = _extras;
3758 intent = _intent;
3759 hint = _hint;
3760 receiver = _receiver;
3761 receiverExtras = _receiverExtras;
3762 userHandle = _userHandle;
3763 }
3764
3765 @Override
3766 public void run() {
3767 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3768 synchronized (this) {
3769 haveResult = true;
3770 notifyAll();
3771 }
3772 pendingAssistExtrasTimedOut(this);
3773 }
3774 }
3775
3776 @Override
3777 public boolean isAssistDataAllowedOnCurrentActivity() {
3778 int userId;
3779 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003780 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003781 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3782 return false;
3783 }
3784
Wale Ogunwale21e06482019-11-18 05:14:15 -08003785 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 if (activity == null) {
3787 return false;
3788 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003789 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003790 }
3791 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3792 }
3793
3794 @Override
3795 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3796 long ident = Binder.clearCallingIdentity();
3797 try {
3798 synchronized (mGlobalLock) {
3799 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003800 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801 if (top != caller) {
3802 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3803 + " is not current top " + top);
3804 return false;
3805 }
3806 if (!top.nowVisible) {
3807 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3808 + " is not visible");
3809 return false;
3810 }
3811 }
3812 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3813 token);
3814 } finally {
3815 Binder.restoreCallingIdentity(ident);
3816 }
3817 }
3818
3819 @Override
3820 public boolean isRootVoiceInteraction(IBinder token) {
3821 synchronized (mGlobalLock) {
3822 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3823 if (r == null) {
3824 return false;
3825 }
3826 return r.rootVoiceInteraction;
3827 }
3828 }
3829
Wale Ogunwalef6733932018-06-27 05:14:34 -07003830 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3831 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3832 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3833 if (activityToCallback == null) return;
3834 activityToCallback.setVoiceSessionLocked(voiceSession);
3835
3836 // Inform the activity
3837 try {
3838 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3839 voiceInteractor);
3840 long token = Binder.clearCallingIdentity();
3841 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003842 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003843 } finally {
3844 Binder.restoreCallingIdentity(token);
3845 }
3846 // TODO: VI Should we cache the activity so that it's easier to find later
3847 // rather than scan through all the stacks and activities?
3848 } catch (RemoteException re) {
3849 activityToCallback.clearVoiceSessionLocked();
3850 // TODO: VI Should this terminate the voice session?
3851 }
3852 }
3853
3854 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3855 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3856 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3857 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3858 boolean wasRunningVoice = mRunningVoice != null;
3859 mRunningVoice = session;
3860 if (!wasRunningVoice) {
3861 mVoiceWakeLock.acquire();
3862 updateSleepIfNeededLocked();
3863 }
3864 }
3865 }
3866
3867 void finishRunningVoiceLocked() {
3868 if (mRunningVoice != null) {
3869 mRunningVoice = null;
3870 mVoiceWakeLock.release();
3871 updateSleepIfNeededLocked();
3872 }
3873 }
3874
3875 @Override
3876 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3877 synchronized (mGlobalLock) {
3878 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3879 if (keepAwake) {
3880 mVoiceWakeLock.acquire();
3881 } else {
3882 mVoiceWakeLock.release();
3883 }
3884 }
3885 }
3886 }
3887
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 @Override
3889 public ComponentName getActivityClassForToken(IBinder token) {
3890 synchronized (mGlobalLock) {
3891 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3892 if (r == null) {
3893 return null;
3894 }
3895 return r.intent.getComponent();
3896 }
3897 }
3898
3899 @Override
3900 public String getPackageForToken(IBinder token) {
3901 synchronized (mGlobalLock) {
3902 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3903 if (r == null) {
3904 return null;
3905 }
3906 return r.packageName;
3907 }
3908 }
3909
3910 @Override
3911 public void showLockTaskEscapeMessage(IBinder token) {
3912 synchronized (mGlobalLock) {
3913 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3914 if (r == null) {
3915 return;
3916 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003917 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 }
3919 }
3920
3921 @Override
3922 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003923 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 final long token = Binder.clearCallingIdentity();
3925 try {
3926 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003927 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 }
3929 } finally {
3930 Binder.restoreCallingIdentity(token);
3931 }
3932 }
3933
3934 /**
3935 * Try to place task to provided position. The final position might be different depending on
3936 * current user and stacks state. The task will be moved to target stack if it's currently in
3937 * different stack.
3938 */
3939 @Override
3940 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003941 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003942 synchronized (mGlobalLock) {
3943 long ident = Binder.clearCallingIdentity();
3944 try {
3945 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3946 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003947 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 if (task == null) {
3949 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3950 + taskId);
3951 }
3952
Louis Chang149d5c82019-12-30 09:47:39 +08003953 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954
3955 if (stack == null) {
3956 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3957 + stackId);
3958 }
3959 if (!stack.isActivityTypeStandardOrUndefined()) {
3960 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3961 + " the position of task " + taskId + " in/to non-standard stack");
3962 }
3963
3964 // TODO: Have the callers of this API call a separate reparent method if that is
3965 // what they intended to do vs. having this method also do reparenting.
3966 if (task.getStack() == stack) {
3967 // Change position in current stack.
3968 stack.positionChildAt(task, position);
3969 } else {
3970 // Reparent to new stack.
3971 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3972 !DEFER_RESUME, "positionTaskInStack");
3973 }
3974 } finally {
3975 Binder.restoreCallingIdentity(ident);
3976 }
3977 }
3978 }
3979
3980 @Override
3981 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3982 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3983 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003984 + Arrays.toString(horizontalSizeConfiguration) + " "
3985 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003986 synchronized (mGlobalLock) {
3987 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3988 if (record == null) {
3989 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3990 + "found for: " + token);
3991 }
3992 record.setSizeConfigurations(horizontalSizeConfiguration,
3993 verticalSizeConfigurations, smallestSizeConfigurations);
3994 }
3995 }
3996
3997 /**
3998 * Dismisses split-screen multi-window mode.
3999 * @param toTop If true the current primary split-screen stack will be placed or left on top.
4000 */
4001 @Override
4002 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004003 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004004 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
4005 final long ident = Binder.clearCallingIdentity();
4006 try {
4007 synchronized (mGlobalLock) {
4008 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004009 mRootWindowContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 if (stack == null) {
4011 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
4012 return;
4013 }
4014
4015 if (toTop) {
4016 // Caller wants the current split-screen primary stack to be the top stack after
4017 // it goes fullscreen, so move it to the front.
4018 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004019 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09004021 // stack after it goes fullscreen, so we move the focus to the top-most
4022 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
4024 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
4025 if (otherStack != null) {
4026 otherStack.moveToFront("dismissSplitScreenMode_other");
4027 }
4028 }
4029
Evan Rosky10475742018-09-05 19:02:48 -07004030 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 }
4032 } finally {
4033 Binder.restoreCallingIdentity(ident);
4034 }
4035 }
4036
4037 /**
4038 * Dismisses Pip
4039 * @param animate True if the dismissal should be animated.
4040 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4041 * default animation duration should be used.
4042 */
4043 @Override
4044 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004045 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 final long ident = Binder.clearCallingIdentity();
4047 try {
4048 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004049 final ActivityStack stack =
Louis Chang149d5c82019-12-30 09:47:39 +08004050 mRootWindowContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004051 if (stack == null) {
4052 Slog.w(TAG, "dismissPip: pinned stack not found.");
4053 return;
4054 }
4055 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4056 throw new IllegalArgumentException("Stack: " + stack
4057 + " doesn't support animated resize.");
4058 }
4059 if (animate) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004060 stack.animateResizePinnedStack(null /* destBounds */,
4061 null /* sourceHintBounds */, animationDuration,
4062 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004064 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 }
4066 }
4067 } finally {
4068 Binder.restoreCallingIdentity(ident);
4069 }
4070 }
4071
4072 @Override
4073 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004074 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 synchronized (mGlobalLock) {
4076 mSuppressResizeConfigChanges = suppress;
4077 }
4078 }
4079
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 @Override
4081 // TODO: API should just be about changing windowing modes...
4082 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004083 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004084 "moveTasksToFullscreenStack()");
4085 synchronized (mGlobalLock) {
4086 final long origId = Binder.clearCallingIdentity();
4087 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004088 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004089 if (stack != null){
4090 if (!stack.isActivityTypeStandardOrUndefined()) {
4091 throw new IllegalArgumentException(
4092 "You can't move tasks from non-standard stacks.");
4093 }
4094 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4095 }
4096 } finally {
4097 Binder.restoreCallingIdentity(origId);
4098 }
4099 }
4100 }
4101
4102 /**
4103 * Moves the top activity in the input stackId to the pinned stack.
4104 *
4105 * @param stackId Id of stack to move the top activity to pinned stack.
4106 * @param bounds Bounds to use for pinned stack.
4107 *
4108 * @return True if the top activity of the input stack was successfully moved to the pinned
4109 * stack.
4110 */
4111 @Override
4112 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004113 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 "moveTopActivityToPinnedStack()");
4115 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004116 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004117 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4118 + "Device doesn't support picture-in-picture mode");
4119 }
4120
4121 long ident = Binder.clearCallingIdentity();
4122 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004123 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 } finally {
4125 Binder.restoreCallingIdentity(ident);
4126 }
4127 }
4128 }
4129
4130 @Override
4131 public boolean isInMultiWindowMode(IBinder token) {
4132 final long origId = Binder.clearCallingIdentity();
4133 try {
4134 synchronized (mGlobalLock) {
4135 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4136 if (r == null) {
4137 return false;
4138 }
4139 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4140 return r.inMultiWindowMode();
4141 }
4142 } finally {
4143 Binder.restoreCallingIdentity(origId);
4144 }
4145 }
4146
4147 @Override
4148 public boolean isInPictureInPictureMode(IBinder token) {
4149 final long origId = Binder.clearCallingIdentity();
4150 try {
4151 synchronized (mGlobalLock) {
4152 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4153 }
4154 } finally {
4155 Binder.restoreCallingIdentity(origId);
4156 }
4157 }
4158
4159 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004160 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4161 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 return false;
4163 }
4164
4165 // If we are animating to fullscreen then we have already dispatched the PIP mode
4166 // changed, so we should reflect that check here as well.
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004167 final ActivityStack taskStack = r.getActivityStack();
Yunfan Chen279f5582018-12-12 15:24:50 -08004168 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004169 }
4170
4171 @Override
4172 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4173 final long origId = Binder.clearCallingIdentity();
4174 try {
4175 synchronized (mGlobalLock) {
4176 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4177 "enterPictureInPictureMode", token, params);
4178
4179 // If the activity is already in picture in picture mode, then just return early
4180 if (isInPictureInPictureMode(r)) {
4181 return true;
4182 }
4183
4184 // Activity supports picture-in-picture, now check that we can enter PiP at this
4185 // point, if it is
4186 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4187 false /* beforeStopping */)) {
4188 return false;
4189 }
4190
4191 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004192 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004193 if (r.getParent() == null) {
4194 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4195 return;
4196 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004197 // Only update the saved args from the args that are set
4198 r.pictureInPictureArgs.copyOnlySet(params);
4199 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4200 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4201 // Adjust the source bounds by the insets for the transition down
4202 final Rect sourceBounds = new Rect(
4203 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004204 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004205 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004206 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004207 stack.setPictureInPictureAspectRatio(aspectRatio);
4208 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004209 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4210 r.info.applicationInfo.uid, r.shortComponentName,
4211 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004212 logPictureInPictureArgs(params);
4213 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004214 };
4215
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004216 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004217 // If the keyguard is showing or occluded, then try and dismiss it before
4218 // entering picture-in-picture (this will prompt the user to authenticate if the
4219 // device is currently locked).
4220 dismissKeyguard(token, new KeyguardDismissCallback() {
4221 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004222 public void onDismissSucceeded() {
4223 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 }
4225 }, null /* message */);
4226 } else {
4227 // Enter picture in picture immediately otherwise
4228 enterPipRunnable.run();
4229 }
4230 return true;
4231 }
4232 } finally {
4233 Binder.restoreCallingIdentity(origId);
4234 }
4235 }
4236
4237 @Override
4238 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4239 final long origId = Binder.clearCallingIdentity();
4240 try {
4241 synchronized (mGlobalLock) {
4242 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4243 "setPictureInPictureParams", token, params);
4244
4245 // Only update the saved args from the args that are set
4246 r.pictureInPictureArgs.copyOnlySet(params);
4247 if (r.inPinnedWindowingMode()) {
4248 // If the activity is already in picture-in-picture, update the pinned stack now
4249 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4250 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004251 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 if (!stack.isAnimatingBoundsToFullscreen()) {
4253 stack.setPictureInPictureAspectRatio(
4254 r.pictureInPictureArgs.getAspectRatio());
4255 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4256 }
4257 }
4258 logPictureInPictureArgs(params);
4259 }
4260 } finally {
4261 Binder.restoreCallingIdentity(origId);
4262 }
4263 }
4264
4265 @Override
4266 public int getMaxNumPictureInPictureActions(IBinder token) {
4267 // Currently, this is a static constant, but later, we may change this to be dependent on
4268 // the context of the activity
4269 return 3;
4270 }
4271
4272 private void logPictureInPictureArgs(PictureInPictureParams params) {
4273 if (params.hasSetActions()) {
4274 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4275 params.getActions().size());
4276 }
4277 if (params.hasSetAspectRatio()) {
4278 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4279 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4280 MetricsLogger.action(lm);
4281 }
4282 }
4283
4284 /**
4285 * Checks the state of the system and the activity associated with the given {@param token} to
4286 * verify that picture-in-picture is supported for that activity.
4287 *
4288 * @return the activity record for the given {@param token} if all the checks pass.
4289 */
4290 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4291 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004292 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 throw new IllegalStateException(caller
4294 + ": Device doesn't support picture-in-picture mode.");
4295 }
4296
4297 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4298 if (r == null) {
4299 throw new IllegalStateException(caller
4300 + ": Can't find activity for token=" + token);
4301 }
4302
4303 if (!r.supportsPictureInPicture()) {
4304 throw new IllegalStateException(caller
4305 + ": Current activity does not support picture-in-picture.");
4306 }
4307
4308 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004309 && !mWindowManager.isValidPictureInPictureAspectRatio(
4310 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 final float minAspectRatio = mContext.getResources().getFloat(
4312 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4313 final float maxAspectRatio = mContext.getResources().getFloat(
4314 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4315 throw new IllegalArgumentException(String.format(caller
4316 + ": Aspect ratio is too extreme (must be between %f and %f).",
4317 minAspectRatio, maxAspectRatio));
4318 }
4319
4320 // Truncate the number of actions if necessary
4321 params.truncateActions(getMaxNumPictureInPictureActions(token));
4322
4323 return r;
4324 }
4325
4326 @Override
4327 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004328 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 synchronized (mGlobalLock) {
4330 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4331 if (r == null) {
4332 throw new IllegalArgumentException("Activity does not exist; token="
4333 + activityToken);
4334 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004335 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004336 }
4337 }
4338
4339 @Override
4340 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4341 Rect tempDockedTaskInsetBounds,
4342 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004343 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004344 long ident = Binder.clearCallingIdentity();
4345 try {
4346 synchronized (mGlobalLock) {
4347 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4348 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4349 PRESERVE_WINDOWS);
4350 }
4351 } finally {
4352 Binder.restoreCallingIdentity(ident);
4353 }
4354 }
4355
4356 @Override
4357 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004358 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 final long ident = Binder.clearCallingIdentity();
4360 try {
4361 synchronized (mGlobalLock) {
4362 mStackSupervisor.setSplitScreenResizing(resizing);
4363 }
4364 } finally {
4365 Binder.restoreCallingIdentity(ident);
4366 }
4367 }
4368
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004369 /**
4370 * Check that we have the features required for VR-related API calls, and throw an exception if
4371 * not.
4372 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004373 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 if (!mContext.getPackageManager().hasSystemFeature(
4375 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4376 throw new UnsupportedOperationException("VR mode not supported on this device!");
4377 }
4378 }
4379
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 @Override
4381 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004382 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383
4384 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4385
4386 ActivityRecord r;
4387 synchronized (mGlobalLock) {
4388 r = ActivityRecord.isInStackLocked(token);
4389 }
4390
4391 if (r == null) {
4392 throw new IllegalArgumentException();
4393 }
4394
4395 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004396 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 VrManagerInternal.NO_ERROR) {
4398 return err;
4399 }
4400
4401 // Clear the binder calling uid since this path may call moveToTask().
4402 final long callingId = Binder.clearCallingIdentity();
4403 try {
4404 synchronized (mGlobalLock) {
4405 r.requestedVrComponent = (enabled) ? packageName : null;
4406
4407 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004408 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004409 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 }
4411 return 0;
4412 }
4413 } finally {
4414 Binder.restoreCallingIdentity(callingId);
4415 }
4416 }
4417
4418 @Override
4419 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4420 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4421 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004422 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4424 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4425 }
Louis Changcdec0802019-11-11 11:45:07 +08004426 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 || activity.voiceSession != null) {
4428 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4429 return;
4430 }
4431 if (activity.pendingVoiceInteractionStart) {
4432 Slog.w(TAG, "Pending start of voice interaction already.");
4433 return;
4434 }
4435 activity.pendingVoiceInteractionStart = true;
4436 }
4437 LocalServices.getService(VoiceInteractionManagerInternal.class)
4438 .startLocalVoiceInteraction(callingActivity, options);
4439 }
4440
4441 @Override
4442 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4443 LocalServices.getService(VoiceInteractionManagerInternal.class)
4444 .stopLocalVoiceInteraction(callingActivity);
4445 }
4446
4447 @Override
4448 public boolean supportsLocalVoiceInteraction() {
4449 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4450 .supportsLocalVoiceInteraction();
4451 }
4452
4453 /** Notifies all listeners when the pinned stack animation starts. */
4454 @Override
4455 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004456 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 }
4458
4459 /** Notifies all listeners when the pinned stack animation ends. */
4460 @Override
4461 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004462 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 }
4464
4465 @Override
4466 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 final long ident = Binder.clearCallingIdentity();
4469 try {
4470 synchronized (mGlobalLock) {
4471 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4472 }
4473 } finally {
4474 Binder.restoreCallingIdentity(ident);
4475 }
4476 }
4477
4478 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004479 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004480 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004481
4482 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004483 if (mWindowManager == null) {
4484 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4485 return false;
4486 }
4487
4488 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004489 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004490 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 }
4492
Riddle Hsua0022cd2019-09-09 21:12:41 +08004493 mH.sendMessage(PooledLambda.obtainMessage(
4494 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4495 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004496
4497 final long origId = Binder.clearCallingIdentity();
4498 try {
4499 if (values != null) {
4500 Settings.System.clearConfiguration(values);
4501 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004502 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 UserHandle.USER_NULL, false /* deferResume */,
4504 mTmpUpdateConfigurationResult);
4505 return mTmpUpdateConfigurationResult.changes != 0;
4506 } finally {
4507 Binder.restoreCallingIdentity(origId);
4508 }
4509 }
4510 }
4511
4512 @Override
4513 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4514 CharSequence message) {
4515 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004516 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4518 }
4519 final long callingId = Binder.clearCallingIdentity();
4520 try {
4521 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004522 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 }
4524 } finally {
4525 Binder.restoreCallingIdentity(callingId);
4526 }
4527 }
4528
4529 @Override
4530 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004531 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004532 "cancelTaskWindowTransition()");
4533 final long ident = Binder.clearCallingIdentity();
4534 try {
4535 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004536 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004537 MATCH_TASK_IN_STACKS_ONLY);
4538 if (task == null) {
4539 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4540 return;
4541 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004542 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 }
4544 } finally {
4545 Binder.restoreCallingIdentity(ident);
4546 }
4547 }
4548
4549 @Override
4550 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004551 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 final long ident = Binder.clearCallingIdentity();
4553 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004554 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004555 } finally {
4556 Binder.restoreCallingIdentity(ident);
4557 }
4558 }
4559
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004560 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4561 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004562 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004563 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004564 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004565 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4566 if (task == null) {
4567 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4568 return null;
4569 }
4570 }
4571 // Don't call this while holding the lock as this operation might hit the disk.
4572 return task.getSnapshot(reducedResolution, restoreFromDisk);
4573 }
4574
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 @Override
4576 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4577 synchronized (mGlobalLock) {
4578 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4579 if (r == null) {
4580 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4581 + token);
4582 return;
4583 }
4584 final long origId = Binder.clearCallingIdentity();
4585 try {
4586 r.setDisablePreviewScreenshots(disable);
4587 } finally {
4588 Binder.restoreCallingIdentity(origId);
4589 }
4590 }
4591 }
4592
Riddle Hsu440f88b2019-11-06 22:17:35 +08004593 @Override
4594 public void invalidateHomeTaskSnapshot(IBinder token) {
4595 synchronized (mGlobalLock) {
4596 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4597 if (r == null || !r.isActivityTypeHome()) {
4598 return;
4599 }
4600 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4601 }
4602 }
4603
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004604 /** Return the user id of the last resumed activity. */
4605 @Override
4606 public @UserIdInt
4607 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004608 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004609 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4610 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004611 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004612 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004613 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004614 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 }
4616 }
4617
4618 @Override
4619 public void updateLockTaskFeatures(int userId, int flags) {
4620 final int callingUid = Binder.getCallingUid();
4621 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004622 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004623 "updateLockTaskFeatures()");
4624 }
4625 synchronized (mGlobalLock) {
4626 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4627 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004628 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004629 }
4630 }
4631
4632 @Override
4633 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4634 synchronized (mGlobalLock) {
4635 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4636 if (r == null) {
4637 return;
4638 }
4639 final long origId = Binder.clearCallingIdentity();
4640 try {
4641 r.setShowWhenLocked(showWhenLocked);
4642 } finally {
4643 Binder.restoreCallingIdentity(origId);
4644 }
4645 }
4646 }
4647
4648 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004649 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4650 synchronized (mGlobalLock) {
4651 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4652 if (r == null) {
4653 return;
4654 }
4655 final long origId = Binder.clearCallingIdentity();
4656 try {
4657 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4658 } finally {
4659 Binder.restoreCallingIdentity(origId);
4660 }
4661 }
4662 }
4663
4664 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004665 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4666 synchronized (mGlobalLock) {
4667 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4668 if (r == null) {
4669 return;
4670 }
4671 final long origId = Binder.clearCallingIdentity();
4672 try {
4673 r.setTurnScreenOn(turnScreenOn);
4674 } finally {
4675 Binder.restoreCallingIdentity(origId);
4676 }
4677 }
4678 }
4679
4680 @Override
4681 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004682 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004683 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004684 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004685 synchronized (mGlobalLock) {
4686 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4687 if (r == null) {
4688 return;
4689 }
4690 final long origId = Binder.clearCallingIdentity();
4691 try {
4692 r.registerRemoteAnimations(definition);
4693 } finally {
4694 Binder.restoreCallingIdentity(origId);
4695 }
4696 }
4697 }
4698
4699 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004700 public void unregisterRemoteAnimations(IBinder token) {
4701 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4702 "unregisterRemoteAnimations");
4703 synchronized (mGlobalLock) {
4704 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4705 if (r == null) {
4706 return;
4707 }
4708 final long origId = Binder.clearCallingIdentity();
4709 try {
4710 r.unregisterRemoteAnimations();
4711 } finally {
4712 Binder.restoreCallingIdentity(origId);
4713 }
4714 }
4715 }
4716
4717 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004718 public void registerRemoteAnimationForNextActivityStart(String packageName,
4719 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004720 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004721 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004722 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004723 synchronized (mGlobalLock) {
4724 final long origId = Binder.clearCallingIdentity();
4725 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004726 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004727 packageName, adapter);
4728 } finally {
4729 Binder.restoreCallingIdentity(origId);
4730 }
4731 }
4732 }
4733
Evan Rosky966759f2019-01-15 10:33:58 -08004734 @Override
4735 public void registerRemoteAnimationsForDisplay(int displayId,
4736 RemoteAnimationDefinition definition) {
4737 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4738 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004739 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004740 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004741 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004742 if (display == null) {
4743 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4744 return;
4745 }
4746 final long origId = Binder.clearCallingIdentity();
4747 try {
4748 display.mDisplayContent.registerRemoteAnimations(definition);
4749 } finally {
4750 Binder.restoreCallingIdentity(origId);
4751 }
4752 }
4753 }
4754
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004755 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4756 @Override
4757 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4758 synchronized (mGlobalLock) {
4759 final long origId = Binder.clearCallingIdentity();
4760 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004761 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004762 } finally {
4763 Binder.restoreCallingIdentity(origId);
4764 }
4765 }
4766 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004767
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004768 @Override
4769 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004770 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004771 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004772 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004773 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004774 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 }
4776 }
4777
4778 @Override
4779 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004780 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 != PERMISSION_GRANTED) {
4782 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4783 + Binder.getCallingPid()
4784 + ", uid=" + Binder.getCallingUid()
4785 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4786 Slog.w(TAG, msg);
4787 throw new SecurityException(msg);
4788 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004789 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004791 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004792 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004793 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 }
4795 }
4796
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004797 @Override
4798 public void stopAppSwitches() {
4799 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4800 synchronized (mGlobalLock) {
4801 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004802 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004803 mDidAppSwitch = false;
4804 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4805 }
4806 }
4807
4808 @Override
4809 public void resumeAppSwitches() {
4810 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4811 synchronized (mGlobalLock) {
4812 // Note that we don't execute any pending app switches... we will
4813 // let those wait until either the timeout, or the next start
4814 // activity request.
4815 mAppSwitchesAllowedTime = 0;
4816 }
4817 }
4818
Ricky Wai906af482019-06-03 17:25:28 +01004819 long getLastStopAppSwitchesTime() {
4820 return mLastStopAppSwitchesTime;
4821 }
4822
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004823 void onStartActivitySetDidAppSwitch() {
4824 if (mDidAppSwitch) {
4825 // This is the second allowed switch since we stopped switches, so now just generally
4826 // allow switches. Use case:
4827 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4828 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4829 // anyone to switch again).
4830 mAppSwitchesAllowedTime = 0;
4831 } else {
4832 mDidAppSwitch = true;
4833 }
4834 }
4835
4836 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004837 boolean shouldDisableNonVrUiLocked() {
4838 return mVrController.shouldDisableNonVrUiLocked();
4839 }
4840
Wale Ogunwale53783742018-09-16 10:21:51 -07004841 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004842 // 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 +00004843 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004844 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004845 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4846 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004847 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004848 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004849 }
4850 mH.post(() -> {
4851 if (!mVrController.onVrModeChanged(r)) {
4852 return;
4853 }
4854 synchronized (mGlobalLock) {
4855 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4856 mWindowManager.disableNonVrUi(disableNonVrUi);
4857 if (disableNonVrUi) {
4858 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4859 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004860 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004861 }
4862 }
4863 });
4864 }
4865
Wale Ogunwale53783742018-09-16 10:21:51 -07004866 @Override
4867 public int getPackageScreenCompatMode(String packageName) {
4868 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4869 synchronized (mGlobalLock) {
4870 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4871 }
4872 }
4873
4874 @Override
4875 public void setPackageScreenCompatMode(String packageName, int mode) {
4876 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4877 "setPackageScreenCompatMode");
4878 synchronized (mGlobalLock) {
4879 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4880 }
4881 }
4882
4883 @Override
4884 public boolean getPackageAskScreenCompat(String packageName) {
4885 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4886 synchronized (mGlobalLock) {
4887 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4888 }
4889 }
4890
4891 @Override
4892 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4893 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4894 "setPackageAskScreenCompat");
4895 synchronized (mGlobalLock) {
4896 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4897 }
4898 }
4899
Wale Ogunwale64258362018-10-16 15:13:37 -07004900 public static String relaunchReasonToString(int relaunchReason) {
4901 switch (relaunchReason) {
4902 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4903 return "window_resize";
4904 case RELAUNCH_REASON_FREE_RESIZE:
4905 return "free_resize";
4906 default:
4907 return null;
4908 }
4909 }
4910
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004911 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004912 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004913 }
4914
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004915 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004916 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004917 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4918 }
4919
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004920 boolean isKeyguardLocked() {
4921 return mKeyguardController.isKeyguardLocked();
4922 }
4923
Garfield Tan01548632018-11-27 10:15:48 -08004924 /**
4925 * Clears launch params for the given package.
4926 * @param packageNames the names of the packages of which the launch params are to be cleared
4927 */
4928 @Override
4929 public void clearLaunchParamsForPackages(List<String> packageNames) {
4930 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4931 "clearLaunchParamsForPackages");
4932 synchronized (mGlobalLock) {
4933 for (int i = 0; i < packageNames.size(); ++i) {
4934 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4935 }
4936 }
4937 }
4938
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004939 /**
4940 * Makes the display with the given id a single task instance display. I.e the display can only
4941 * contain one task.
4942 */
4943 @Override
4944 public void setDisplayToSingleTaskInstance(int displayId) {
4945 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4946 "setDisplayToSingleTaskInstance");
4947 final long origId = Binder.clearCallingIdentity();
4948 try {
Louis Chang677921f2019-12-06 16:44:24 +08004949 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004950 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004951 if (display != null) {
4952 display.setDisplayToSingleTaskInstance();
4953 }
4954 } finally {
4955 Binder.restoreCallingIdentity(origId);
4956 }
4957 }
4958
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004959 /**
4960 * Requests that an activity should enter picture-in-picture mode if possible.
4961 */
4962 @Override
4963 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4964 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4965 "requestPictureInPictureMode");
4966 final long origId = Binder.clearCallingIdentity();
4967 try {
4968 synchronized (mGlobalLock) {
4969 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4970 if (activity == null) {
4971 return;
4972 }
4973
4974 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4975 "requestPictureInPictureMode", /* beforeStopping */ false);
4976 if (!canEnterPictureInPicture) {
4977 throw new IllegalStateException(
4978 "Requested PIP on an activity that doesn't support it");
4979 }
4980
4981 try {
4982 final ClientTransaction transaction = ClientTransaction.obtain(
4983 activity.app.getThread(),
4984 activity.token);
4985 transaction.addCallback(EnterPipRequestedItem.obtain());
4986 getLifecycleManager().scheduleTransaction(transaction);
4987 } catch (Exception e) {
4988 Slog.w(TAG, "Failed to send enter pip requested item: "
4989 + activity.intent.getComponent(), e);
4990 }
4991 }
4992 } finally {
4993 Binder.restoreCallingIdentity(origId);
4994 }
4995 }
4996
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 void dumpLastANRLocked(PrintWriter pw) {
4998 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4999 if (mLastANRState == null) {
5000 pw.println(" <no ANR has occurred since boot>");
5001 } else {
5002 pw.println(mLastANRState);
5003 }
5004 }
5005
5006 void dumpLastANRTracesLocked(PrintWriter pw) {
5007 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5008
5009 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5010 if (ArrayUtils.isEmpty(files)) {
5011 pw.println(" <no ANR has occurred since boot>");
5012 return;
5013 }
5014 // Find the latest file.
5015 File latest = null;
5016 for (File f : files) {
5017 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5018 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005019 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005020 }
5021 pw.print("File: ");
5022 pw.print(latest.getName());
5023 pw.println();
5024 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5025 String line;
5026 while ((line = in.readLine()) != null) {
5027 pw.println(line);
5028 }
5029 } catch (IOException e) {
5030 pw.print("Unable to read: ");
5031 pw.print(e);
5032 pw.println();
5033 }
5034 }
5035
5036 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5037 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5038 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5039 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5040 }
5041
5042 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5043 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5044 pw.println(header);
5045
Louis Chang149d5c82019-12-30 09:47:39 +08005046 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005047 dumpPackage);
5048 boolean needSep = printedAnything;
5049
5050 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005051 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005052 " ResumedActivity: ");
5053 if (printed) {
5054 printedAnything = true;
5055 needSep = false;
5056 }
5057
5058 if (dumpPackage == null) {
5059 if (needSep) {
5060 pw.println();
5061 }
5062 printedAnything = true;
5063 mStackSupervisor.dump(pw, " ");
5064 }
5065
5066 if (!printedAnything) {
5067 pw.println(" (nothing)");
5068 }
5069 }
5070
5071 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005072 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005073 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005074 pw.println(" ");
5075 }
5076
5077 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5078 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5079 getActivityStartController().dump(pw, "", dumpPackage);
5080 }
5081
5082 /**
5083 * There are three things that cmd can be:
5084 * - a flattened component name that matches an existing activity
5085 * - the cmd arg isn't the flattened component name of an existing activity:
5086 * dump all activity whose component contains the cmd as a substring
5087 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005088 * <p>
5089 * The caller should not hold lock when calling this method because it will wait for the
5090 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005091 *
5092 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5093 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5094 */
5095 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5096 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5097 ArrayList<ActivityRecord> activities;
5098
5099 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005100 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005101 dumpFocusedStackOnly);
5102 }
5103
5104 if (activities.size() <= 0) {
5105 return false;
5106 }
5107
5108 String[] newArgs = new String[args.length - opti];
5109 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5110
Louis Changcdec0802019-11-11 11:45:07 +08005111 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005112 boolean needSep = false;
5113 for (int i = activities.size() - 1; i >= 0; i--) {
5114 ActivityRecord r = activities.get(i);
5115 if (needSep) {
5116 pw.println();
5117 }
5118 needSep = true;
5119 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005120 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005121 if (lastTask != task) {
5122 lastTask = task;
5123 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005124 pw.print(" id="); pw.print(lastTask.mTaskId);
5125 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005126 if (dumpAll) {
5127 lastTask.dump(pw, " ");
5128 }
5129 }
5130 }
5131 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5132 }
5133 return true;
5134 }
5135
5136 /**
5137 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5138 * there is a thread associated with the activity.
5139 */
5140 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5141 final ActivityRecord r, String[] args, boolean dumpAll) {
5142 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005143 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005144 synchronized (mGlobalLock) {
5145 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5146 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5147 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005148 if (r.hasProcess()) {
5149 pw.println(r.app.getPid());
5150 appThread = r.app.getThread();
5151 } else {
5152 pw.println("(not running)");
5153 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005154 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005155 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005156 }
5157 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005158 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005159 // flush anything that is already in the PrintWriter since the thread is going
5160 // to write to the file descriptor directly
5161 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005162 try (TransferPipe tp = new TransferPipe()) {
5163 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5164 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005165 } catch (IOException e) {
5166 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5167 } catch (RemoteException e) {
5168 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5169 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005170 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005171 }
5172
sanryhuang498e77e2018-12-06 14:57:01 +08005173 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5174 boolean testPssMode) {
5175 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5176 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5177 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005178 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005179 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5180 st.toString());
5181 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005182 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5183 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5184 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005185 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5186 testPssMode);
5187 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005188 }
5189
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190 int getCurrentUserId() {
5191 return mAmInternal.getCurrentUserId();
5192 }
5193
5194 private void enforceNotIsolatedCaller(String caller) {
5195 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5196 throw new SecurityException("Isolated process not allowed to call " + caller);
5197 }
5198 }
5199
Wale Ogunwalef6733932018-06-27 05:14:34 -07005200 public Configuration getConfiguration() {
5201 Configuration ci;
5202 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005203 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005204 ci.userSetLocale = false;
5205 }
5206 return ci;
5207 }
5208
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005209 /**
5210 * Current global configuration information. Contains general settings for the entire system,
5211 * also corresponds to the merged configuration of the default display.
5212 */
5213 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005214 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005215 // while initializing process record for system, see {@link
5216 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005217 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005218 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
5220
5221 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5222 boolean initLocale) {
5223 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5224 }
5225
5226 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5227 boolean initLocale, boolean deferResume) {
5228 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5229 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5230 UserHandle.USER_NULL, deferResume);
5231 }
5232
Wale Ogunwale59507092018-10-29 09:00:30 -07005233 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234 final long origId = Binder.clearCallingIdentity();
5235 try {
5236 synchronized (mGlobalLock) {
5237 updateConfigurationLocked(values, null, false, true, userId,
5238 false /* deferResume */);
5239 }
5240 } finally {
5241 Binder.restoreCallingIdentity(origId);
5242 }
5243 }
5244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005245 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5246 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5247 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5248 deferResume, null /* result */);
5249 }
5250
5251 /**
5252 * Do either or both things: (1) change the current configuration, and (2)
5253 * make sure the given activity is running with the (now) current
5254 * configuration. Returns true if the activity has been left running, or
5255 * false if <var>starting</var> is being destroyed to match the new
5256 * configuration.
5257 *
5258 * @param userId is only used when persistent parameter is set to true to persist configuration
5259 * for that particular user
5260 */
5261 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5262 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5263 ActivityTaskManagerService.UpdateConfigurationResult result) {
5264 int changes = 0;
5265 boolean kept = true;
5266
Riddle Hsua0022cd2019-09-09 21:12:41 +08005267 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268 try {
5269 if (values != null) {
5270 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5271 deferResume);
5272 }
5273
5274 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5275 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005276 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005277 }
5278
5279 if (result != null) {
5280 result.changes = changes;
5281 result.activityRelaunched = !kept;
5282 }
5283 return kept;
5284 }
5285
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005286 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005287 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005289
Louis Chang677921f2019-12-06 16:44:24 +08005290 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005291 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005292
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005293 mTempConfig.setTo(getGlobalConfiguration());
5294 final int changes = mTempConfig.updateFrom(values);
5295 if (changes == 0) {
5296 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5297 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5298 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5299 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005300 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005301 return 0;
5302 }
5303
5304 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5305 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005306 writeConfigurationChanged(changes);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5308 values.colorMode,
5309 values.densityDpi,
5310 values.fontScale,
5311 values.hardKeyboardHidden,
5312 values.keyboard,
5313 values.keyboardHidden,
5314 values.mcc,
5315 values.mnc,
5316 values.navigation,
5317 values.navigationHidden,
5318 values.orientation,
5319 values.screenHeightDp,
5320 values.screenLayout,
5321 values.screenWidthDp,
5322 values.smallestScreenWidthDp,
5323 values.touchscreen,
5324 values.uiMode);
5325
5326
5327 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5328 final LocaleList locales = values.getLocales();
5329 int bestLocaleIndex = 0;
5330 if (locales.size() > 1) {
5331 if (mSupportedSystemLocales == null) {
5332 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5333 }
5334 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5335 }
5336 SystemProperties.set("persist.sys.locale",
5337 locales.get(bestLocaleIndex).toLanguageTag());
5338 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005339
5340 final Message m = PooledLambda.obtainMessage(
5341 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5342 locales.get(bestLocaleIndex));
5343 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344 }
5345
Yunfan Chen75157d72018-07-27 14:47:21 +09005346 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005347
5348 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005349 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005350
5351 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5352 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005353 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005354
5355 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005357
5358 AttributeCache ac = AttributeCache.instance();
5359 if (ac != null) {
5360 ac.updateConfiguration(mTempConfig);
5361 }
5362
5363 // Make sure all resources in our process are updated right now, so that anyone who is going
5364 // to retrieve resource values after we return will be sure to get the new ones. This is
5365 // especially important during boot, where the first config change needs to guarantee all
5366 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005367 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005368
5369 // We need another copy of global config because we're scheduling some calls instead of
5370 // running them in place. We need to be sure that object we send will be handled unchanged.
5371 final Configuration configCopy = new Configuration(mTempConfig);
5372 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005373 final Message msg = PooledLambda.obtainMessage(
5374 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5375 this, userId, configCopy);
5376 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005377 }
5378
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005379 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5380 for (int i = pidMap.size() - 1; i >= 0; i--) {
5381 final int pid = pidMap.keyAt(i);
5382 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005383 if (DEBUG_CONFIGURATION) {
5384 Slog.v(TAG_CONFIGURATION, "Update process config of "
5385 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005386 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005387 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005388 }
5389
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005390 final Message msg = PooledLambda.obtainMessage(
5391 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5392 mAmInternal, changes, initLocale);
5393 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005394
5395 // Override configuration of the default display duplicates global config, so we need to
5396 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005397 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005398 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005399
5400 return changes;
5401 }
5402
Riddle Hsua0022cd2019-09-09 21:12:41 +08005403 /** @see WindowSurfacePlacer#deferLayout */
5404 void deferWindowLayout() {
5405 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5406 // Reset the reasons at the first entrance because we only care about the changes in the
5407 // deferred scope.
5408 mLayoutReasons = 0;
5409 }
5410
5411 mWindowManager.mWindowPlacerLocked.deferLayout();
5412 }
5413
5414 /** @see WindowSurfacePlacer#continueLayout */
5415 void continueWindowLayout() {
5416 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5417 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5418 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5419 }
5420 }
5421
5422 /**
5423 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5424 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5425 * defer count is gone.
5426 */
5427 void addWindowLayoutReasons(@LayoutReason int reasons) {
5428 mLayoutReasons |= reasons;
5429 }
5430
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 private void updateEventDispatchingLocked(boolean booted) {
5432 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5433 }
5434
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005435 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5436 final ContentResolver resolver = mContext.getContentResolver();
5437 Settings.System.putConfigurationForUser(resolver, config, userId);
5438 }
5439
5440 private void sendLocaleToMountDaemonMsg(Locale l) {
5441 try {
5442 IBinder service = ServiceManager.getService("mount");
5443 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5444 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5445 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5446 } catch (RemoteException e) {
5447 Log.e(TAG, "Error storing locale for decryption UI", e);
5448 }
5449 }
5450
Alison Cichowlas3e340502018-08-07 17:15:01 -04005451 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5452 mStartActivitySources.remove(permissionToken);
5453 mExpiredStartAsCallerTokens.add(permissionToken);
5454 }
5455
5456 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5457 mExpiredStartAsCallerTokens.remove(permissionToken);
5458 }
5459
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005460 boolean isActivityStartsLoggingEnabled() {
5461 return mAmInternal.isActivityStartsLoggingEnabled();
5462 }
5463
Michal Karpinski8596ded2018-11-14 14:43:48 +00005464 boolean isBackgroundActivityStartsEnabled() {
5465 return mAmInternal.isBackgroundActivityStartsEnabled();
5466 }
5467
Wale Ogunwalef6733932018-06-27 05:14:34 -07005468 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005469 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005470 mWindowManager.enableScreenAfterBoot();
5471
5472 synchronized (mGlobalLock) {
5473 updateEventDispatchingLocked(booted);
5474 }
5475 }
5476
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005477 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5478 if (r == null || !r.hasProcess()) {
5479 return KEY_DISPATCHING_TIMEOUT_MS;
5480 }
5481 return getInputDispatchingTimeoutLocked(r.app);
5482 }
5483
5484 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005485 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005486 }
5487
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488 /**
5489 * Decide based on the configuration whether we should show the ANR,
5490 * crash, etc dialogs. The idea is that if there is no affordance to
5491 * press the on-screen buttons, or the user experience would be more
5492 * greatly impacted than the crash itself, we shouldn't show the dialog.
5493 *
5494 * A thought: SystemUI might also want to get told about this, the Power
5495 * dialog / global actions also might want different behaviors.
5496 */
5497 private void updateShouldShowDialogsLocked(Configuration config) {
5498 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5499 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5500 && config.navigation == Configuration.NAVIGATION_NONAV);
5501 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5502 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5503 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5504 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5505 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5506 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5507 HIDE_ERROR_DIALOGS, 0) != 0;
5508 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5509 }
5510
5511 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5512 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5513 FONT_SCALE, 1.0f, userId);
5514
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005515 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005516 if (getGlobalConfiguration().fontScale == scaleFactor) {
5517 return;
5518 }
5519
5520 final Configuration configuration
5521 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5522 configuration.fontScale = scaleFactor;
5523 updatePersistentConfiguration(configuration, userId);
5524 }
5525 }
5526
5527 // Actually is sleeping or shutting down or whatever else in the future
5528 // is an inactive state.
5529 boolean isSleepingOrShuttingDownLocked() {
5530 return isSleepingLocked() || mShuttingDown;
5531 }
5532
5533 boolean isSleepingLocked() {
5534 return mSleeping;
5535 }
5536
Riddle Hsu16567132018-08-16 21:37:47 +08005537 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005538 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005539 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005540 if (task.isActivityTypeStandard()) {
5541 if (mCurAppTimeTracker != r.appTimeTracker) {
5542 // We are switching app tracking. Complete the current one.
5543 if (mCurAppTimeTracker != null) {
5544 mCurAppTimeTracker.stop();
5545 mH.obtainMessage(
5546 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005547 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 mCurAppTimeTracker = null;
5549 }
5550 if (r.appTimeTracker != null) {
5551 mCurAppTimeTracker = r.appTimeTracker;
5552 startTimeTrackingFocusedActivityLocked();
5553 }
5554 } else {
5555 startTimeTrackingFocusedActivityLocked();
5556 }
5557 } else {
5558 r.appTimeTracker = null;
5559 }
5560 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5561 // TODO: Probably not, because we don't want to resume voice on switching
5562 // back to this activity
5563 if (task.voiceInteractor != null) {
5564 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5565 } else {
5566 finishRunningVoiceLocked();
5567
5568 if (mLastResumedActivity != null) {
5569 final IVoiceInteractionSession session;
5570
Louis Changcdec0802019-11-11 11:45:07 +08005571 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005572 if (lastResumedActivityTask != null
5573 && lastResumedActivityTask.voiceSession != null) {
5574 session = lastResumedActivityTask.voiceSession;
5575 } else {
5576 session = mLastResumedActivity.voiceSession;
5577 }
5578
5579 if (session != null) {
5580 // We had been in a voice interaction session, but now focused has
5581 // move to something different. Just finish the session, we can't
5582 // return to it and retain the proper state and synchronization with
5583 // the voice interaction service.
5584 finishVoiceTask(session);
5585 }
5586 }
5587 }
5588
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005589 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5590 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591 }
5592 updateResumedAppTrace(r);
5593 mLastResumedActivity = r;
5594
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005595 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005596
5597 applyUpdateLockStateLocked(r);
5598 applyUpdateVrModeLocked(r);
5599
Jeff Changd136e772019-11-05 20:33:52 +08005600 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005601 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005602 r == null ? "NULL" : r.shortComponentName,
5603 reason);
5604 }
5605
5606 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5607 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005608 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005609 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005610 updateSleepIfNeededLocked();
5611 return token;
5612 }
5613 }
5614
5615 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005616 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005617 final boolean wasSleeping = mSleeping;
5618 boolean updateOomAdj = false;
5619
5620 if (!shouldSleep) {
5621 // If wasSleeping is true, we need to wake up activity manager state from when
5622 // we started sleeping. In either case, we need to apply the sleep tokens, which
5623 // will wake up stacks or put them to sleep as appropriate.
5624 if (wasSleeping) {
5625 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005626 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5627 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005628 startTimeTrackingFocusedActivityLocked();
5629 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005630 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005631 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5632 }
Louis Chang149d5c82019-12-30 09:47:39 +08005633 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005634 if (wasSleeping) {
5635 updateOomAdj = true;
5636 }
5637 } else if (!mSleeping && shouldSleep) {
5638 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005639 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5640 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005641 if (mCurAppTimeTracker != null) {
5642 mCurAppTimeTracker.stop();
5643 }
5644 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005645 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005646 mStackSupervisor.goingToSleepLocked();
5647 updateResumedAppTrace(null /* resumed */);
5648 updateOomAdj = true;
5649 }
5650 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005651 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005652 }
5653 }
5654
5655 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005656 mH.removeCallbacks(mUpdateOomAdjRunnable);
5657 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005658 }
5659
Wale Ogunwale53783742018-09-16 10:21:51 -07005660 void updateCpuStats() {
5661 mH.post(mAmInternal::updateCpuStats);
5662 }
5663
Hui Yu03d12402018-12-06 18:00:37 -08005664 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5665 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005666 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5667 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005668 mH.sendMessage(m);
5669 }
5670
Hui Yu03d12402018-12-06 18:00:37 -08005671 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005672 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005673 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005674 if (task != null) {
5675 final ActivityRecord rootActivity = task.getRootActivity();
5676 if (rootActivity != null) {
5677 taskRoot = rootActivity.mActivityComponent;
5678 }
5679 }
5680
Hui Yu03d12402018-12-06 18:00:37 -08005681 final Message m = PooledLambda.obtainMessage(
5682 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005683 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005684 mH.sendMessage(m);
5685 }
5686
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005687 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5688 String hostingType) {
5689 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005690 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5691 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005692 + activity.processName);
5693 }
5694 // Post message to start process to avoid possible deadlock of calling into AMS with the
5695 // ATMS lock held.
5696 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5697 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5698 isTop, hostingType, activity.intent.getComponent());
5699 mH.sendMessage(m);
5700 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005701 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005702 }
5703 }
5704
Wale Ogunwale53783742018-09-16 10:21:51 -07005705 void setBooting(boolean booting) {
5706 mAmInternal.setBooting(booting);
5707 }
5708
5709 boolean isBooting() {
5710 return mAmInternal.isBooting();
5711 }
5712
5713 void setBooted(boolean booted) {
5714 mAmInternal.setBooted(booted);
5715 }
5716
5717 boolean isBooted() {
5718 return mAmInternal.isBooted();
5719 }
5720
5721 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5722 mH.post(() -> {
5723 if (finishBooting) {
5724 mAmInternal.finishBooting();
5725 }
5726 if (enableScreen) {
5727 mInternal.enableScreenAfterBoot(isBooted());
5728 }
5729 });
5730 }
5731
5732 void setHeavyWeightProcess(ActivityRecord root) {
5733 mHeavyWeightProcess = root.app;
5734 final Message m = PooledLambda.obtainMessage(
5735 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005736 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005737 mH.sendMessage(m);
5738 }
5739
5740 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5741 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5742 return;
5743 }
5744
5745 mHeavyWeightProcess = null;
5746 final Message m = PooledLambda.obtainMessage(
5747 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5748 proc.mUserId);
5749 mH.sendMessage(m);
5750 }
5751
5752 private void cancelHeavyWeightProcessNotification(int userId) {
5753 final INotificationManager inm = NotificationManager.getService();
5754 if (inm == null) {
5755 return;
5756 }
5757 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005758 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005759 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5760 } catch (RuntimeException e) {
5761 Slog.w(TAG, "Error canceling notification for service", e);
5762 } catch (RemoteException e) {
5763 }
5764
5765 }
5766
5767 private void postHeavyWeightProcessNotification(
5768 WindowProcessController proc, Intent intent, int userId) {
5769 if (proc == null) {
5770 return;
5771 }
5772
5773 final INotificationManager inm = NotificationManager.getService();
5774 if (inm == null) {
5775 return;
5776 }
5777
5778 try {
5779 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5780 String text = mContext.getString(R.string.heavy_weight_notification,
5781 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5782 Notification notification =
5783 new Notification.Builder(context,
5784 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5785 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5786 .setWhen(0)
5787 .setOngoing(true)
5788 .setTicker(text)
5789 .setColor(mContext.getColor(
5790 com.android.internal.R.color.system_notification_accent_color))
5791 .setContentTitle(text)
5792 .setContentText(
5793 mContext.getText(R.string.heavy_weight_notification_detail))
5794 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5795 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5796 new UserHandle(userId)))
5797 .build();
5798 try {
5799 inm.enqueueNotificationWithTag("android", "android", null,
5800 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5801 } catch (RuntimeException e) {
5802 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5803 } catch (RemoteException e) {
5804 }
5805 } catch (PackageManager.NameNotFoundException e) {
5806 Slog.w(TAG, "Unable to create context for heavy notification", e);
5807 }
5808
5809 }
5810
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005811 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5812 IBinder token, String resultWho, int requestCode, Intent[] intents,
5813 String[] resolvedTypes, int flags, Bundle bOptions) {
5814
5815 ActivityRecord activity = null;
5816 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5817 activity = ActivityRecord.isInStackLocked(token);
5818 if (activity == null) {
5819 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5820 return null;
5821 }
5822 if (activity.finishing) {
5823 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5824 return null;
5825 }
5826 }
5827
5828 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5829 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5830 bOptions);
5831 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5832 if (noCreate) {
5833 return rec;
5834 }
5835 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5836 if (activity.pendingResults == null) {
5837 activity.pendingResults = new HashSet<>();
5838 }
5839 activity.pendingResults.add(rec.ref);
5840 }
5841 return rec;
5842 }
5843
Andrii Kulian52d255c2018-07-13 11:32:19 -07005844 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005845 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005846 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005847 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5848 mCurAppTimeTracker.start(resumedActivity.packageName);
5849 }
5850 }
5851
5852 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5853 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005854 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005855 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5856 }
5857 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005858 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005859 constructResumedTraceName(resumed.packageName), 0);
5860 }
5861 mTracedResumedActivity = resumed;
5862 }
5863
5864 private String constructResumedTraceName(String packageName) {
5865 return "focused app: " + packageName;
5866 }
5867
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005868 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005869 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005870 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005871 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005872 // mainStack is null during startup.
5873 if (mainStack != null) {
5874 if (changes != 0 && starting == null) {
5875 // If the configuration changed, and the caller is not already
5876 // in the process of starting an activity, then find the top
5877 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005878 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005879 }
5880
5881 if (starting != null) {
5882 kept = starting.ensureActivityConfiguration(changes,
5883 false /* preserveWindow */);
5884 // And we need to make sure at this point that all other activities
5885 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005886 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005887 !PRESERVE_WINDOWS);
5888 }
5889 }
5890
5891 return kept;
5892 }
5893
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005894 void scheduleAppGcsLocked() {
5895 mH.post(() -> mAmInternal.scheduleAppGcs());
5896 }
5897
Wale Ogunwale53783742018-09-16 10:21:51 -07005898 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5899 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5900 }
5901
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005902 /**
5903 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5904 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5905 * on demand.
5906 */
5907 IPackageManager getPackageManager() {
5908 return AppGlobals.getPackageManager();
5909 }
5910
5911 PackageManagerInternal getPackageManagerInternalLocked() {
5912 if (mPmInternal == null) {
5913 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5914 }
5915 return mPmInternal;
5916 }
5917
Hai Zhangf4da9be2019-05-01 13:46:06 +08005918 PermissionPolicyInternal getPermissionPolicyInternal() {
5919 if (mPermissionPolicyInternal == null) {
5920 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5921 }
5922 return mPermissionPolicyInternal;
5923 }
5924
Wale Ogunwale008163e2018-07-23 23:11:08 -07005925 AppWarnings getAppWarningsLocked() {
5926 return mAppWarnings;
5927 }
5928
Wale Ogunwale214f3482018-10-04 11:00:47 -07005929 Intent getHomeIntent() {
5930 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5931 intent.setComponent(mTopComponent);
5932 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5933 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5934 intent.addCategory(Intent.CATEGORY_HOME);
5935 }
5936 return intent;
5937 }
5938
Chilun2ef71f72018-11-16 17:57:15 +08005939 /**
5940 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5941 * activities.
5942 *
5943 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5944 * component defined in config_secondaryHomeComponent.
5945 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5946 */
5947 Intent getSecondaryHomeIntent(String preferredPackage) {
5948 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005949 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5950 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5951 if (preferredPackage == null || useSystemProvidedLauncher) {
5952 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005953 final String secondaryHomeComponent = mContext.getResources().getString(
5954 com.android.internal.R.string.config_secondaryHomeComponent);
5955 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5956 } else {
5957 intent.setPackage(preferredPackage);
5958 }
5959 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5960 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5961 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5962 }
5963 return intent;
5964 }
5965
Wale Ogunwale214f3482018-10-04 11:00:47 -07005966 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5967 if (info == null) return null;
5968 ApplicationInfo newInfo = new ApplicationInfo(info);
5969 newInfo.initForUser(userId);
5970 return newInfo;
5971 }
5972
Wale Ogunwale9c103022018-10-18 07:44:54 -07005973 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005974 if (uid == SYSTEM_UID) {
5975 // The system gets to run in any process. If there are multiple processes with the same
5976 // uid, just pick the first (this should never happen).
5977 final SparseArray<WindowProcessController> procs =
5978 mProcessNames.getMap().get(processName);
5979 if (procs == null) return null;
5980 final int procCount = procs.size();
5981 for (int i = 0; i < procCount; i++) {
5982 final int procUid = procs.keyAt(i);
5983 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5984 // Don't use an app process or different user process for system component.
5985 continue;
5986 }
5987 return procs.valueAt(i);
5988 }
5989 }
5990
5991 return mProcessNames.get(processName, uid);
5992 }
5993
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005994 WindowProcessController getProcessController(IApplicationThread thread) {
5995 if (thread == null) {
5996 return null;
5997 }
5998
5999 final IBinder threadBinder = thread.asBinder();
6000 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6001 for (int i = pmap.size()-1; i >= 0; i--) {
6002 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6003 for (int j = procs.size() - 1; j >= 0; j--) {
6004 final WindowProcessController proc = procs.valueAt(j);
6005 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6006 return proc;
6007 }
6008 }
6009 }
6010
6011 return null;
6012 }
6013
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006014 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006015 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006016 if (proc == null) return null;
6017 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6018 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006019 }
6020 return null;
6021 }
6022
Riddle Hsua0536432019-02-16 00:38:59 +08006023 int getUidState(int uid) {
6024 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006025 }
6026
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006027 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006028 // A uid is considered to be foreground if it has a visible non-toast window.
6029 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006030 }
6031
Ricky Wai96f5c352019-04-10 18:40:17 +01006032 boolean isDeviceOwner(int uid) {
6033 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006034 }
6035
Ricky Wai96f5c352019-04-10 18:40:17 +01006036 void setDeviceOwnerUid(int uid) {
6037 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006038 }
6039
Wale Ogunwale9de19442018-10-18 19:05:03 -07006040 /**
6041 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6042 * the whitelist
6043 */
6044 String getPendingTempWhitelistTagForUidLocked(int uid) {
6045 return mPendingTempWhitelist.get(uid);
6046 }
6047
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006048 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6049 if (true || Build.IS_USER) {
6050 return;
6051 }
6052
6053 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6054 StrictMode.allowThreadDiskWrites();
6055 try {
6056 File tracesDir = new File("/data/anr");
6057 File tracesFile = null;
6058 try {
6059 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6060
6061 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006062 String timeString =
6063 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6064 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006065 sb.append(": ");
6066 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6067 sb.append(" since ");
6068 sb.append(msg);
6069 FileOutputStream fos = new FileOutputStream(tracesFile);
6070 fos.write(sb.toString().getBytes());
6071 if (app == null) {
6072 fos.write("\n*** No application process!".getBytes());
6073 }
6074 fos.close();
6075 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6076 } catch (IOException e) {
6077 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6078 return;
6079 }
6080
6081 if (app != null && app.getPid() > 0) {
6082 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6083 firstPids.add(app.getPid());
6084 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6085 }
6086
6087 File lastTracesFile = null;
6088 File curTracesFile = null;
6089 for (int i=9; i>=0; i--) {
6090 String name = String.format(Locale.US, "slow%02d.txt", i);
6091 curTracesFile = new File(tracesDir, name);
6092 if (curTracesFile.exists()) {
6093 if (lastTracesFile != null) {
6094 curTracesFile.renameTo(lastTracesFile);
6095 } else {
6096 curTracesFile.delete();
6097 }
6098 }
6099 lastTracesFile = curTracesFile;
6100 }
6101 tracesFile.renameTo(curTracesFile);
6102 } finally {
6103 StrictMode.setThreadPolicy(oldPolicy);
6104 }
6105 }
6106
Michal Karpinskida34cd42019-04-02 19:46:52 +01006107 boolean isAssociatedCompanionApp(int userId, int uid) {
6108 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6109 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006110 return false;
6111 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006112 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006113 }
6114
Issei Suzuki734bc942019-06-05 13:59:52 +02006115 void notifySingleTaskDisplayEmpty(int displayId) {
6116 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6117 }
6118
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006119 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006120 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006121
6122
Wale Ogunwale98875612018-10-12 07:53:02 -07006123 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6124 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006125
Riddle Hsud93a6c42018-11-29 21:50:06 +08006126 H(Looper looper) {
6127 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006128 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006129
6130 @Override
6131 public void handleMessage(Message msg) {
6132 switch (msg.what) {
6133 case REPORT_TIME_TRACKER_MSG: {
6134 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6135 tracker.deliverResult(mContext);
6136 } break;
6137 }
6138 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006139 }
6140
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006141 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006142 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006143
6144 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006145 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006146 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006147
6148 @Override
6149 public void handleMessage(Message msg) {
6150 switch (msg.what) {
6151 case DISMISS_DIALOG_UI_MSG: {
6152 final Dialog d = (Dialog) msg.obj;
6153 d.dismiss();
6154 break;
6155 }
6156 }
6157 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006158 }
6159
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006160 final class LocalService extends ActivityTaskManagerInternal {
6161 @Override
6162 public SleepToken acquireSleepToken(String tag, int displayId) {
6163 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006164 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006165 }
6166
6167 @Override
6168 public ComponentName getHomeActivityForUser(int userId) {
6169 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006170 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006171 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006172 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006173 }
6174 }
6175
6176 @Override
6177 public void onLocalVoiceInteractionStarted(IBinder activity,
6178 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6179 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006180 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182 }
6183
6184 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006185 public void notifySingleTaskDisplayDrawn(int displayId) {
6186 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6187 }
6188
6189 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006190 public void notifyAppTransitionFinished() {
6191 synchronized (mGlobalLock) {
6192 mStackSupervisor.notifyAppTransitionDone();
6193 }
6194 }
6195
6196 @Override
6197 public void notifyAppTransitionCancelled() {
6198 synchronized (mGlobalLock) {
6199 mStackSupervisor.notifyAppTransitionDone();
6200 }
6201 }
6202
6203 @Override
6204 public List<IBinder> getTopVisibleActivities() {
6205 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006206 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 }
6208 }
6209
6210 @Override
6211 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6212 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006213 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 }
6215 }
6216
6217 @Override
6218 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6219 Bundle bOptions) {
6220 Preconditions.checkNotNull(intents, "intents");
6221 final String[] resolvedTypes = new String[intents.length];
6222
6223 // UID of the package on user userId.
6224 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6225 // packageUid may not be initialized.
6226 int packageUid = 0;
6227 final long ident = Binder.clearCallingIdentity();
6228
6229 try {
6230 for (int i = 0; i < intents.length; i++) {
6231 resolvedTypes[i] =
6232 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6233 }
6234
6235 packageUid = AppGlobals.getPackageManager().getPackageUid(
6236 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6237 } catch (RemoteException e) {
6238 // Shouldn't happen.
6239 } finally {
6240 Binder.restoreCallingIdentity(ident);
6241 }
6242
Riddle Hsu591bf612019-02-14 17:55:31 +08006243 return getActivityStartController().startActivitiesInPackage(
6244 packageUid, packageName,
6245 intents, resolvedTypes, null /* resultTo */,
6246 SafeActivityOptions.fromBundle(bOptions), userId,
6247 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6248 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
6250
6251 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006252 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6253 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6254 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6255 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006256 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006257 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006258 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6259 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6260 userId, validateIncomingUser, originatingPendingIntent,
6261 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006262 }
6263 }
6264
6265 @Override
6266 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6267 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6268 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
Louis Changcdec0802019-11-11 11:45:07 +08006269 int userId, Task inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006270 PendingIntentRecord originatingPendingIntent,
6271 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006272 synchronized (mGlobalLock) {
6273 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6274 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6275 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006276 validateIncomingUser, originatingPendingIntent,
6277 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006278 }
6279 }
6280
6281 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006282 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6283 Intent intent, Bundle options, int userId) {
6284 return ActivityTaskManagerService.this.startActivityAsUser(
6285 caller, callerPacakge, intent,
6286 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6287 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6288 false /*validateIncomingUser*/);
6289 }
6290
6291 @Override
lumark588a3e82018-07-20 18:53:54 +08006292 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006293 synchronized (mGlobalLock) {
6294
6295 // We might change the visibilities here, so prepare an empty app transition which
6296 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006297 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006298 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006299 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006300 return;
6301 }
Louis Chang677921f2019-12-06 16:44:24 +08006302 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006303 final boolean wasTransitionSet =
6304 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006305 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006306 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006307 }
Louis Chang149d5c82019-12-30 09:47:39 +08006308 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309
6310 // If there was a transition set already we don't want to interfere with it as we
6311 // might be starting it too early.
6312 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006313 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006314 }
6315 }
6316 if (callback != null) {
6317 callback.run();
6318 }
6319 }
6320
6321 @Override
6322 public void notifyKeyguardTrustedChanged() {
6323 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006324 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006325 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006326 }
6327 }
6328 }
6329
6330 /**
6331 * Called after virtual display Id is updated by
6332 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6333 * {@param vrVr2dDisplayId}.
6334 */
6335 @Override
6336 public void setVr2dDisplayId(int vr2dDisplayId) {
6337 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6338 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006339 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006340 }
6341 }
6342
6343 @Override
6344 public void setFocusedActivity(IBinder token) {
6345 synchronized (mGlobalLock) {
6346 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6347 if (r == null) {
6348 throw new IllegalArgumentException(
6349 "setFocusedActivity: No activity record matching token=" + token);
6350 }
Louis Chang19443452018-10-09 12:10:21 +08006351 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006352 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006353 }
6354 }
6355 }
6356
6357 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006358 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006359 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006360 }
6361
6362 @Override
6363 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006364 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006365 }
6366
6367 @Override
6368 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006369 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006370 }
6371
6372 @Override
6373 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6374 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6375 }
6376
6377 @Override
6378 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006379 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006380 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006381
6382 @Override
6383 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6384 synchronized (mGlobalLock) {
6385 mActiveVoiceInteractionServiceComponent = component;
6386 }
6387 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006388
6389 @Override
6390 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6391 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6392 return;
6393 }
6394 synchronized (mGlobalLock) {
6395 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6396 if (types == null) {
6397 if (uid < 0) {
6398 return;
6399 }
6400 types = new ArrayMap<>();
6401 mAllowAppSwitchUids.put(userId, types);
6402 }
6403 if (uid < 0) {
6404 types.remove(type);
6405 } else {
6406 types.put(type, uid);
6407 }
6408 }
6409 }
6410
6411 @Override
6412 public void onUserStopped(int userId) {
6413 synchronized (mGlobalLock) {
6414 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6415 mAllowAppSwitchUids.remove(userId);
6416 }
6417 }
6418
6419 @Override
6420 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6421 synchronized (mGlobalLock) {
6422 return ActivityTaskManagerService.this.isGetTasksAllowed(
6423 caller, callingPid, callingUid);
6424 }
6425 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006426
Riddle Hsua0536432019-02-16 00:38:59 +08006427 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006428 @Override
6429 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006430 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006431 mProcessNames.put(proc.mName, proc.mUid, proc);
6432 }
6433 }
6434
Riddle Hsua0536432019-02-16 00:38:59 +08006435 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006436 @Override
6437 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006438 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006439 mProcessNames.remove(name, uid);
6440 }
6441 }
6442
Riddle Hsua0536432019-02-16 00:38:59 +08006443 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006444 @Override
6445 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006446 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006447 if (proc == mHomeProcess) {
6448 mHomeProcess = null;
6449 }
6450 if (proc == mPreviousProcess) {
6451 mPreviousProcess = null;
6452 }
6453 }
6454 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006455
Riddle Hsua0536432019-02-16 00:38:59 +08006456 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006457 @Override
6458 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006459 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006460 return mTopProcessState;
6461 }
6462 }
6463
Riddle Hsua0536432019-02-16 00:38:59 +08006464 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006465 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006466 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006467 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006468 return proc == mHeavyWeightProcess;
6469 }
6470 }
6471
Riddle Hsua0536432019-02-16 00:38:59 +08006472 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006473 @Override
6474 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006475 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006476 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6477 }
6478 }
6479
6480 @Override
6481 public void finishHeavyWeightApp() {
6482 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006483 if (mHeavyWeightProcess != null) {
6484 mHeavyWeightProcess.finishActivities();
6485 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006486 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6487 mHeavyWeightProcess);
6488 }
6489 }
6490
Riddle Hsua0536432019-02-16 00:38:59 +08006491 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006492 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006493 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006494 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006495 return isSleepingLocked();
6496 }
6497 }
6498
6499 @Override
6500 public boolean isShuttingDown() {
6501 synchronized (mGlobalLock) {
6502 return mShuttingDown;
6503 }
6504 }
6505
6506 @Override
6507 public boolean shuttingDown(boolean booted, int timeout) {
6508 synchronized (mGlobalLock) {
6509 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006510 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006511 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006512 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006513 return mStackSupervisor.shutdownLocked(timeout);
6514 }
6515 }
6516
6517 @Override
6518 public void enableScreenAfterBoot(boolean booted) {
6519 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006520 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006521 mWindowManager.enableScreenAfterBoot();
6522 updateEventDispatchingLocked(booted);
6523 }
6524 }
6525
6526 @Override
6527 public boolean showStrictModeViolationDialog() {
6528 synchronized (mGlobalLock) {
6529 return mShowDialogs && !mSleeping && !mShuttingDown;
6530 }
6531 }
6532
6533 @Override
6534 public void showSystemReadyErrorDialogsIfNeeded() {
6535 synchronized (mGlobalLock) {
6536 try {
6537 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6538 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6539 + " data partition or your device will be unstable.");
6540 mUiHandler.post(() -> {
6541 if (mShowDialogs) {
6542 AlertDialog d = new BaseErrorDialog(mUiContext);
6543 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6544 d.setCancelable(false);
6545 d.setTitle(mUiContext.getText(R.string.android_system_label));
6546 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6547 d.setButton(DialogInterface.BUTTON_POSITIVE,
6548 mUiContext.getText(R.string.ok),
6549 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6550 d.show();
6551 }
6552 });
6553 }
6554 } catch (RemoteException e) {
6555 }
6556
6557 if (!Build.isBuildConsistent()) {
6558 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6559 mUiHandler.post(() -> {
6560 if (mShowDialogs) {
6561 AlertDialog d = new BaseErrorDialog(mUiContext);
6562 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6563 d.setCancelable(false);
6564 d.setTitle(mUiContext.getText(R.string.android_system_label));
6565 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6566 d.setButton(DialogInterface.BUTTON_POSITIVE,
6567 mUiContext.getText(R.string.ok),
6568 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6569 d.show();
6570 }
6571 });
6572 }
6573 }
6574 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006575
6576 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006577 public void onProcessMapped(int pid, WindowProcessController proc) {
6578 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006579 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006580 }
6581 }
6582
6583 @Override
6584 public void onProcessUnMapped(int pid) {
6585 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006586 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006587 }
6588 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006589
6590 @Override
6591 public void onPackageDataCleared(String name) {
6592 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006593 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006594 mAppWarnings.onPackageDataCleared(name);
6595 }
6596 }
6597
6598 @Override
6599 public void onPackageUninstalled(String name) {
6600 synchronized (mGlobalLock) {
6601 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006602 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006603 }
6604 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006605
6606 @Override
6607 public void onPackageAdded(String name, boolean replacing) {
6608 synchronized (mGlobalLock) {
6609 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6610 }
6611 }
6612
6613 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006614 public void onPackageReplaced(ApplicationInfo aInfo) {
6615 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006616 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006617 }
6618 }
6619
6620 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006621 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6622 synchronized (mGlobalLock) {
6623 return compatibilityInfoForPackageLocked(ai);
6624 }
6625 }
6626
Yunfan Chen75157d72018-07-27 14:47:21 +09006627 /**
6628 * Set the corresponding display information for the process global configuration. To be
6629 * called when we need to show IME on a different display.
6630 *
6631 * @param pid The process id associated with the IME window.
6632 * @param displayId The ID of the display showing the IME.
6633 */
6634 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006635 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006636 // Don't update process-level configuration for Multi-Client IME process since other
6637 // IMEs on other displays will also receive this configuration change due to IME
6638 // services use the same application config/context.
6639 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006640
Yunfan Chen75157d72018-07-27 14:47:21 +09006641 if (pid == MY_PID || pid < 0) {
6642 if (DEBUG_CONFIGURATION) {
6643 Slog.w(TAG,
6644 "Trying to update display configuration for system/invalid process.");
6645 }
6646 return;
6647 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006648 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006649 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006650 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006651 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006652 // Call might come when display is not yet added or has been removed.
6653 if (DEBUG_CONFIGURATION) {
6654 Slog.w(TAG, "Trying to update display configuration for non-existing "
6655 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006656 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006657 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006658 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006659 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006660 if (process == null) {
6661 if (DEBUG_CONFIGURATION) {
6662 Slog.w(TAG, "Trying to update display configuration for invalid "
6663 + "process, pid=" + pid);
6664 }
6665 return;
6666 }
lumarkddc77fb2019-06-27 22:22:23 +08006667 process.mIsImeProcess = true;
Louis Chang677921f2019-12-06 16:44:24 +08006668 process.registerDisplayConfigurationListenerLocked(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006669 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006670 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006671
6672 @Override
6673 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006674 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006675 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006676 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6677 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006678 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006679 }
6680 }
6681 }
6682
6683 @Override
6684 public void clearPendingResultForActivity(IBinder activityToken,
6685 WeakReference<PendingIntentRecord> pir) {
6686 synchronized (mGlobalLock) {
6687 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6688 if (r != null && r.pendingResults != null) {
6689 r.pendingResults.remove(pir);
6690 }
6691 }
6692 }
6693
6694 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006695 public ActivityTokens getTopActivityForTask(int taskId) {
6696 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006697 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006698 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006699 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6700 + " Requested task not found");
6701 return null;
6702 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006703 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006704 if (activity == null) {
6705 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6706 + " Requested activity not found");
6707 return null;
6708 }
6709 if (!activity.attachedToProcess()) {
6710 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6711 + activity);
6712 return null;
6713 }
6714 return new ActivityTokens(activity.appToken, activity.assistToken,
6715 activity.app.getThread());
6716 }
6717 }
6718
6719 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006720 public IIntentSender getIntentSender(int type, String packageName,
6721 int callingUid, int userId, IBinder token, String resultWho,
6722 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6723 Bundle bOptions) {
6724 synchronized (mGlobalLock) {
6725 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6726 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6727 }
6728 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006729
6730 @Override
6731 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6732 synchronized (mGlobalLock) {
6733 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6734 if (r == null) {
6735 return null;
6736 }
6737 if (r.mServiceConnectionsHolder == null) {
6738 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6739 ActivityTaskManagerService.this, r);
6740 }
6741
6742 return r.mServiceConnectionsHolder;
6743 }
6744 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006745
6746 @Override
6747 public Intent getHomeIntent() {
6748 synchronized (mGlobalLock) {
6749 return ActivityTaskManagerService.this.getHomeIntent();
6750 }
6751 }
6752
6753 @Override
6754 public boolean startHomeActivity(int userId, String reason) {
6755 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006756 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006757 }
6758 }
6759
6760 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006761 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006762 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006763 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006764 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006765 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006766 }
Chilun8b1f1be2019-03-13 17:14:36 +08006767 }
6768
6769 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006770 public boolean startHomeOnAllDisplays(int userId, String reason) {
6771 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006772 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006773 }
6774 }
6775
Riddle Hsua0536432019-02-16 00:38:59 +08006776 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006777 @Override
6778 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006779 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006780 if (mFactoryTest == FACTORY_TEST_OFF) {
6781 return false;
6782 }
6783 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6784 && wpc.mName.equals(mTopComponent.getPackageName())) {
6785 return true;
6786 }
6787 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6788 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6789 }
6790 }
6791
6792 @Override
6793 public void updateTopComponentForFactoryTest() {
6794 synchronized (mGlobalLock) {
6795 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6796 return;
6797 }
6798 final ResolveInfo ri = mContext.getPackageManager()
6799 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6800 final CharSequence errorMsg;
6801 if (ri != null) {
6802 final ActivityInfo ai = ri.activityInfo;
6803 final ApplicationInfo app = ai.applicationInfo;
6804 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6805 mTopAction = Intent.ACTION_FACTORY_TEST;
6806 mTopData = null;
6807 mTopComponent = new ComponentName(app.packageName, ai.name);
6808 errorMsg = null;
6809 } else {
6810 errorMsg = mContext.getResources().getText(
6811 com.android.internal.R.string.factorytest_not_system);
6812 }
6813 } else {
6814 errorMsg = mContext.getResources().getText(
6815 com.android.internal.R.string.factorytest_no_action);
6816 }
6817 if (errorMsg == null) {
6818 return;
6819 }
6820
6821 mTopAction = null;
6822 mTopData = null;
6823 mTopComponent = null;
6824 mUiHandler.post(() -> {
6825 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6826 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006827 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006828 });
6829 }
6830 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006831
Riddle Hsua0536432019-02-16 00:38:59 +08006832 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 @Override
6834 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6835 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006836 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006838 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006839
6840 wpc.clearRecentTasks();
6841 wpc.clearActivities();
6842
6843 if (wpc.isInstrumenting()) {
6844 finishInstrumentationCallback.run();
6845 }
6846
Jorim Jaggid0752812018-10-16 16:07:20 +02006847 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006848 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006849 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006850 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006851 // If there was nothing to resume, and we are not already restarting
6852 // this process, but there is a visible activity that is hosted by the
6853 // process...then make sure all visible activities are running, taking
6854 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006855 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006856 !PRESERVE_WINDOWS);
6857 }
6858 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006859 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 }
6862 }
6863 }
6864
6865 @Override
6866 public void closeSystemDialogs(String reason) {
6867 enforceNotIsolatedCaller("closeSystemDialogs");
6868
6869 final int pid = Binder.getCallingPid();
6870 final int uid = Binder.getCallingUid();
6871 final long origId = Binder.clearCallingIdentity();
6872 try {
6873 synchronized (mGlobalLock) {
6874 // Only allow this from foreground processes, so that background
6875 // applications can't abuse it to prevent system UI from being shown.
6876 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006877 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 if (!proc.isPerceptible()) {
6879 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6880 + " from background process " + proc);
6881 return;
6882 }
6883 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006884 mWindowManager.closeSystemDialogs(reason);
6885
Louis Chang149d5c82019-12-30 09:47:39 +08006886 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006887 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006888 // Call into AM outside the synchronized block.
6889 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006890 } finally {
6891 Binder.restoreCallingIdentity(origId);
6892 }
6893 }
6894
6895 @Override
6896 public void cleanupDisabledPackageComponents(
6897 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6898 synchronized (mGlobalLock) {
6899 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006900 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006901 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006902 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006903 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 }
6905
6906 // Clean-up disabled tasks
6907 getRecentTasks().cleanupDisabledPackageTasksLocked(
6908 packageName, disabledClasses, userId);
6909 }
6910 }
6911
6912 @Override
6913 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6914 int userId) {
6915 synchronized (mGlobalLock) {
6916
6917 boolean didSomething =
6918 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006919 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006920 null, doit, evenPersistent, userId);
6921 return didSomething;
6922 }
6923 }
6924
6925 @Override
6926 public void resumeTopActivities(boolean scheduleIdle) {
6927 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006928 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006930 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006931 }
6932 }
6933 }
6934
Riddle Hsua0536432019-02-16 00:38:59 +08006935 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006936 @Override
6937 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006938 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006939 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6940 }
6941 }
6942
Riddle Hsua0536432019-02-16 00:38:59 +08006943 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006944 @Override
6945 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006946 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006947 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6948 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6949 }
6950 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006951 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006952 } finally {
6953 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6954 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006955 }
6956 }
6957
6958 @Override
6959 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6960 try {
6961 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6962 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6963 }
6964 } catch (RemoteException ex) {
6965 throw new SecurityException("Fail to check is caller a privileged app", ex);
6966 }
6967
6968 synchronized (mGlobalLock) {
6969 final long ident = Binder.clearCallingIdentity();
6970 try {
6971 if (mAmInternal.shouldConfirmCredentials(userId)) {
6972 if (mKeyguardController.isKeyguardLocked()) {
6973 // Showing launcher to avoid user entering credential twice.
6974 startHomeActivity(currentUserId, "notifyLockedProfile");
6975 }
Louis Chang149d5c82019-12-30 09:47:39 +08006976 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006977 }
6978 } finally {
6979 Binder.restoreCallingIdentity(ident);
6980 }
6981 }
6982 }
6983
6984 @Override
6985 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6986 mAmInternal.enforceCallingPermission(
6987 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6988
6989 synchronized (mGlobalLock) {
6990 final long ident = Binder.clearCallingIdentity();
6991 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006992 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6993 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006994 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6996 UserHandle.CURRENT);
6997 } finally {
6998 Binder.restoreCallingIdentity(ident);
6999 }
7000 }
7001 }
7002
7003 @Override
7004 public void writeActivitiesToProto(ProtoOutputStream proto) {
7005 synchronized (mGlobalLock) {
7006 // The output proto of "activity --proto activities"
7007 // is ActivityManagerServiceDumpActivitiesProto
Louis Chang149d5c82019-12-30 09:47:39 +08007008 mRootWindowContainer.dumpDebug(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08007009 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
7010 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007011 }
7012 }
7013
7014 @Override
7015 public void saveANRState(String reason) {
7016 synchronized (mGlobalLock) {
7017 final StringWriter sw = new StringWriter();
7018 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7019 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7020 if (reason != null) {
7021 pw.println(" Reason: " + reason);
7022 }
7023 pw.println();
7024 getActivityStartController().dump(pw, " ", null);
7025 pw.println();
7026 pw.println("-------------------------------------------------------------------------------");
7027 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7028 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7029 "" /* header */);
7030 pw.println();
7031 pw.close();
7032
7033 mLastANRState = sw.toString();
7034 }
7035 }
7036
7037 @Override
7038 public void clearSavedANRState() {
7039 synchronized (mGlobalLock) {
7040 mLastANRState = null;
7041 }
7042 }
7043
7044 @Override
7045 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7046 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7047 synchronized (mGlobalLock) {
7048 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7049 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7050 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7051 dumpLastANRLocked(pw);
7052 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7053 dumpLastANRTracesLocked(pw);
7054 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7055 dumpActivityStarterLocked(pw, dumpPackage);
7056 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7057 dumpActivityContainersLocked(pw);
7058 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7059 if (getRecentTasks() != null) {
7060 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7061 }
7062 }
7063 }
7064 }
7065
7066 @Override
7067 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7068 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7069 int wakefulness) {
7070 synchronized (mGlobalLock) {
7071 if (mHomeProcess != null && (dumpPackage == null
7072 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7073 if (needSep) {
7074 pw.println();
7075 needSep = false;
7076 }
7077 pw.println(" mHomeProcess: " + mHomeProcess);
7078 }
7079 if (mPreviousProcess != null && (dumpPackage == null
7080 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7081 if (needSep) {
7082 pw.println();
7083 needSep = false;
7084 }
7085 pw.println(" mPreviousProcess: " + mPreviousProcess);
7086 }
7087 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7088 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7089 StringBuilder sb = new StringBuilder(128);
7090 sb.append(" mPreviousProcessVisibleTime: ");
7091 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7092 pw.println(sb);
7093 }
7094 if (mHeavyWeightProcess != null && (dumpPackage == null
7095 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7096 if (needSep) {
7097 pw.println();
7098 needSep = false;
7099 }
7100 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7101 }
7102 if (dumpPackage == null) {
7103 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007104 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007105 }
7106 if (dumpAll) {
7107 if (dumpPackage == null) {
7108 pw.println(" mConfigWillChange: "
7109 + getTopDisplayFocusedStack().mConfigWillChange);
7110 }
7111 if (mCompatModePackages.getPackages().size() > 0) {
7112 boolean printed = false;
7113 for (Map.Entry<String, Integer> entry
7114 : mCompatModePackages.getPackages().entrySet()) {
7115 String pkg = entry.getKey();
7116 int mode = entry.getValue();
7117 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7118 continue;
7119 }
7120 if (!printed) {
7121 pw.println(" mScreenCompatPackages:");
7122 printed = true;
7123 }
7124 pw.println(" " + pkg + ": " + mode);
7125 }
7126 }
7127 }
7128
7129 if (dumpPackage == null) {
7130 pw.println(" mWakefulness="
7131 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007132 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007133 if (mRunningVoice != null) {
7134 pw.println(" mRunningVoice=" + mRunningVoice);
7135 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7136 }
7137 pw.println(" mSleeping=" + mSleeping);
7138 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7139 pw.println(" mVrController=" + mVrController);
7140 }
7141 if (mCurAppTimeTracker != null) {
7142 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7143 }
7144 if (mAllowAppSwitchUids.size() > 0) {
7145 boolean printed = false;
7146 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7147 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7148 for (int j = 0; j < types.size(); j++) {
7149 if (dumpPackage == null ||
7150 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7151 if (needSep) {
7152 pw.println();
7153 needSep = false;
7154 }
7155 if (!printed) {
7156 pw.println(" mAllowAppSwitchUids:");
7157 printed = true;
7158 }
7159 pw.print(" User ");
7160 pw.print(mAllowAppSwitchUids.keyAt(i));
7161 pw.print(": Type ");
7162 pw.print(types.keyAt(j));
7163 pw.print(" = ");
7164 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7165 pw.println();
7166 }
7167 }
7168 }
7169 }
7170 if (dumpPackage == null) {
7171 if (mController != null) {
7172 pw.println(" mController=" + mController
7173 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7174 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007175 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7176 pw.println(" mLaunchingActivityWakeLock="
7177 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007178 }
7179
7180 return needSep;
7181 }
7182 }
7183
7184 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007185 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7186 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007187 synchronized (mGlobalLock) {
7188 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007189 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007191 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7192 if (mRunningVoice != null) {
7193 final long vrToken = proto.start(
7194 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7195 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7196 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007197 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007198 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7199 proto.end(vrToken);
7200 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007201 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007202 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 if (mController != null) {
7204 final long token = proto.start(CONTROLLER);
7205 proto.write(CONTROLLER, mController.toString());
7206 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7207 proto.end(token);
7208 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007209 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7210 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007211 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007212 }
7213
7214 if (mHomeProcess != null && (dumpPackage == null
7215 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007216 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007217 }
7218
7219 if (mPreviousProcess != null && (dumpPackage == null
7220 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007221 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7223 }
7224
7225 if (mHeavyWeightProcess != null && (dumpPackage == null
7226 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007227 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007228 }
7229
7230 for (Map.Entry<String, Integer> entry
7231 : mCompatModePackages.getPackages().entrySet()) {
7232 String pkg = entry.getKey();
7233 int mode = entry.getValue();
7234 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7235 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7236 proto.write(PACKAGE, pkg);
7237 proto.write(MODE, mode);
7238 proto.end(compatToken);
7239 }
7240 }
7241
7242 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007243 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245
7246 }
7247 }
7248
7249 @Override
7250 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7251 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7252 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007253 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7254 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007255 }
7256
7257 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007258 public void dumpForOom(PrintWriter pw) {
7259 synchronized (mGlobalLock) {
7260 pw.println(" mHomeProcess: " + mHomeProcess);
7261 pw.println(" mPreviousProcess: " + mPreviousProcess);
7262 if (mHeavyWeightProcess != null) {
7263 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7264 }
7265 }
7266 }
7267
7268 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007269 public boolean canGcNow() {
7270 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007271 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007272 }
7273 }
7274
Riddle Hsua0536432019-02-16 00:38:59 +08007275 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007276 @Override
7277 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007278 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007279 if (mRootWindowContainer == null) {
7280 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007281 // oomadj after AMS created.
7282 return null;
7283 }
Louis Chang149d5c82019-12-30 09:47:39 +08007284 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007285 return top != null ? top.app : null;
7286 }
7287 }
7288
Riddle Hsua0536432019-02-16 00:38:59 +08007289 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007290 @Override
7291 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007292 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007293 if (mRootWindowContainer != null) {
7294 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007295 }
7296 }
7297 }
7298
7299 @Override
7300 public void scheduleDestroyAllActivities(String reason) {
7301 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007302 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007303 }
7304 }
7305
7306 @Override
7307 public void removeUser(int userId) {
7308 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007309 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007310 }
7311 }
7312
7313 @Override
7314 public boolean switchUser(int userId, UserState userState) {
7315 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007316 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007317 }
7318 }
7319
7320 @Override
7321 public void onHandleAppCrash(WindowProcessController wpc) {
7322 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007323 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007324 }
7325 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007326
7327 @Override
7328 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7329 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007330 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007331 }
7332 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007333
Riddle Hsua0536432019-02-16 00:38:59 +08007334 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007335 @Override
7336 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007337 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007338 }
7339
Riddle Hsua0536432019-02-16 00:38:59 +08007340 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007341 @Override
7342 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007343 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007344 }
7345
Riddle Hsua0536432019-02-16 00:38:59 +08007346 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007347 @Override
7348 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007349 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007350 }
7351
Riddle Hsua0536432019-02-16 00:38:59 +08007352 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007353 @Override
7354 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007355 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007356 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007357
7358 @Override
7359 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007360 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007361 mPendingTempWhitelist.put(uid, tag);
7362 }
7363 }
7364
7365 @Override
7366 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007368 mPendingTempWhitelist.remove(uid);
7369 }
7370 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007371
7372 @Override
7373 public boolean handleAppCrashInActivityController(String processName, int pid,
7374 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7375 Runnable killCrashingAppCallback) {
7376 synchronized (mGlobalLock) {
7377 if (mController == null) {
7378 return false;
7379 }
7380
7381 try {
7382 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7383 stackTrace)) {
7384 killCrashingAppCallback.run();
7385 return true;
7386 }
7387 } catch (RemoteException e) {
7388 mController = null;
7389 Watchdog.getInstance().setActivityController(null);
7390 }
7391 return false;
7392 }
7393 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007394
7395 @Override
7396 public void removeRecentTasksByPackageName(String packageName, int userId) {
7397 synchronized (mGlobalLock) {
7398 mRecentTasks.removeTasksByPackageName(packageName, userId);
7399 }
7400 }
7401
7402 @Override
7403 public void cleanupRecentTasksForUser(int userId) {
7404 synchronized (mGlobalLock) {
7405 mRecentTasks.cleanupLocked(userId);
7406 }
7407 }
7408
7409 @Override
7410 public void loadRecentTasksForUser(int userId) {
7411 synchronized (mGlobalLock) {
7412 mRecentTasks.loadUserRecentsLocked(userId);
7413 }
7414 }
7415
7416 @Override
7417 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7418 synchronized (mGlobalLock) {
7419 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7420 }
7421 }
7422
7423 @Override
7424 public void flushRecentTasks() {
7425 mRecentTasks.flush();
7426 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007427
7428 @Override
7429 public WindowProcessController getHomeProcess() {
7430 synchronized (mGlobalLock) {
7431 return mHomeProcess;
7432 }
7433 }
7434
7435 @Override
7436 public WindowProcessController getPreviousProcess() {
7437 synchronized (mGlobalLock) {
7438 return mPreviousProcess;
7439 }
7440 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007441
7442 @Override
7443 public void clearLockedTasks(String reason) {
7444 synchronized (mGlobalLock) {
7445 getLockTaskController().clearLockedTasks(reason);
7446 }
7447 }
7448
7449 @Override
7450 public void updateUserConfiguration() {
7451 synchronized (mGlobalLock) {
7452 final Configuration configuration = new Configuration(getGlobalConfiguration());
7453 final int currentUserId = mAmInternal.getCurrentUserId();
7454 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7455 configuration, currentUserId, Settings.System.canWrite(mContext));
7456 updateConfigurationLocked(configuration, null /* starting */,
7457 false /* initLocale */, false /* persistent */, currentUserId,
7458 false /* deferResume */);
7459 }
7460 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007461
7462 @Override
7463 public boolean canShowErrorDialogs() {
7464 synchronized (mGlobalLock) {
7465 return mShowDialogs && !mSleeping && !mShuttingDown
7466 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7467 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7468 mAmInternal.getCurrentUserId())
7469 && !(UserManager.isDeviceInDemoMode(mContext)
7470 && mAmInternal.getCurrentUser().isDemo());
7471 }
7472 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007473
7474 @Override
7475 public void setProfileApp(String profileApp) {
7476 synchronized (mGlobalLock) {
7477 mProfileApp = profileApp;
7478 }
7479 }
7480
7481 @Override
7482 public void setProfileProc(WindowProcessController wpc) {
7483 synchronized (mGlobalLock) {
7484 mProfileProc = wpc;
7485 }
7486 }
7487
7488 @Override
7489 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7490 synchronized (mGlobalLock) {
7491 mProfilerInfo = profilerInfo;
7492 }
7493 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007494
7495 @Override
7496 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7497 synchronized (mGlobalLock) {
7498 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7499 }
7500 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007501
7502 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007503 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7504 boolean reducedResolution) {
7505 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7506 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007507 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007508
7509 @Override
7510 public boolean isUidForeground(int uid) {
7511 synchronized (mGlobalLock) {
7512 return ActivityTaskManagerService.this.isUidForeground(uid);
7513 }
7514 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007515
7516 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007517 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007518 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007519 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007520 }
7521 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007522
7523 @Override
7524 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007525 // Translate package names into UIDs
7526 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007527 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007528 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7529 if (uid >= 0) {
7530 result.add(uid);
7531 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007532 }
7533 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007534 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007535 }
7536 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007537 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007538}