blob: dfc9aa806373e2351fe8ea1dad020bbeff261b5b [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Jonathan Scott92335342019-12-17 14:46:26 +000031import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
40import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Riddle Hsu2ca561b2019-10-08 21:58:58 +080054import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070059import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
60import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070061import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040062import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.view.Display.DEFAULT_DISPLAY;
64import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070065import static android.view.WindowManager.TRANSIT_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070066
Yunfan Chen79b96062018-10-17 12:45:23 -070067import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
70import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwalef342f062020-01-27 07:34:13 -080071import static com.android.server.am.ActivityManagerServiceDumpActivitiesProto.ROOT_WINDOW_CONTAINER;
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;
Evan Rosky0037e5f2019-11-05 10:26:24 -0800147import android.app.ITaskOrganizerController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.Notification;
150import android.app.NotificationManager;
151import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.PictureInPictureParams;
153import android.app.ProfilerInfo;
154import android.app.RemoteAction;
155import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700156import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.app.admin.DevicePolicyCache;
158import android.app.assist.AssistContent;
159import android.app.assist.AssistStructure;
jorgegil@google.com06bc3232019-10-31 14:51:22 -0700160import android.app.servertransaction.ClientTransaction;
161import android.app.servertransaction.EnterPipRequestedItem;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800196import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100201import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700204import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700205import android.os.SystemClock;
206import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700207import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700208import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700210import android.os.UserManager;
211import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700212import android.os.storage.IStorageManager;
213import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.provider.Settings;
Galia Peycheva6861e912019-08-21 10:20:23 +0200215import android.service.dreams.DreamActivity;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700216import android.service.voice.IVoiceInteractionSession;
217import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900218import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700219import android.telecom.TelecomManager;
220import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100221import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700223import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700224import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700225import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700226import android.util.SparseArray;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700227import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700228import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700229import android.view.IRecentsAnimationRunner;
230import android.view.RemoteAnimationAdapter;
231import android.view.RemoteAnimationDefinition;
Evan Roskyaf9f27c2020-02-18 18:58:35 +0000232import android.view.WindowContainerTransaction;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700234
Evan Rosky4505b352018-09-06 11:20:40 -0700235import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700236import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.AssistUtils;
238import 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;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -0800250import com.android.internal.util.FrameworkStatsLog;
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;
Wale Ogunwale59507092018-10-29 09:00:30 -0700261import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
262import com.android.server.am.AppTimeTracker;
263import com.android.server.am.BaseErrorDialog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700264import com.android.server.am.PendingIntentController;
265import com.android.server.am.PendingIntentRecord;
266import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700267import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700268import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800270import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700271import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700275import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700279import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700280import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700281import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800282import java.lang.annotation.ElementType;
283import java.lang.annotation.Retention;
284import java.lang.annotation.RetentionPolicy;
285import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700289import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700290import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400291import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700292import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700294import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700295import java.util.Map;
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +0000296import java.util.Objects;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700297import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
299/**
300 * System service for managing activities and their containers (task, stacks, displays,... ).
301 *
302 * {@hide}
303 */
304public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700305 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale8f93b642019-12-26 12:10:52 -0800306 static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale196db712019-12-27 15:35:39 +0000307 static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700308 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
309 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
310 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
311 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700312 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700313
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700314 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700315 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700317 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100318 // How long we permit background activity starts after an activity in the process
319 // started or finished.
320 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700321
Wale Ogunwale98875612018-10-12 07:53:02 -0700322 /** Used to indicate that an app transition should be animated. */
323 static final boolean ANIMATE = true;
324
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700325 /** Hardware-reported OpenGLES version. */
326 final int GL_ES_VERSION;
327
Wale Ogunwale31913b52018-10-13 08:29:31 -0700328 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
329 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
330 public static final String DUMP_LASTANR_CMD = "lastanr" ;
331 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
332 public static final String DUMP_STARTER_CMD = "starter" ;
333 public static final String DUMP_CONTAINERS_CMD = "containers" ;
334 public static final String DUMP_RECENTS_CMD = "recents" ;
335 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
336
Wale Ogunwale64258362018-10-16 15:13:37 -0700337 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
338 public static final int RELAUNCH_REASON_NONE = 0;
339 /** This activity is being relaunched due to windowing mode change. */
340 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
341 /** This activity is being relaunched due to a free-resize operation. */
342 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
343
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700344 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700345
Wale Ogunwalef6733932018-06-27 05:14:34 -0700346 /**
347 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
348 * change at runtime. Use mContext for non-UI purposes.
349 */
350 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700352 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700353 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700354 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700355 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700356 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800357 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800358 @VisibleForTesting
359 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 PowerManagerInternal mPowerManagerInternal;
361 private UsageStatsManagerInternal mUsageStatsInternal;
362
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700363 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700364 IntentFirewall mIntentFirewall;
365
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700366 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800367 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800368 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700369 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800370 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
371 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
372 *
373 * @see WindowManagerThreadPriorityBooster
374 */
375 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 ActivityStackSupervisor mStackSupervisor;
Louis Chang149d5c82019-12-30 09:47:39 +0800377 RootWindowContainer mRootWindowContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700378 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700379 private UserManagerService mUserManager;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800380 private AppOpsManager mAppOpsManager;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700381 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800382 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700383 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** All processes currently running that might have a window organized by name. */
385 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100386 /** All processes we currently have running mapped by pid and uid */
387 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /** This is the process holding what we currently consider to be the "home" activity. */
389 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700390 /** The currently running heavy-weight process, if any. */
391 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700392 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700393 /**
394 * This is the process holding the activity the user last visited that is in a different process
395 * from the one they are currently in.
396 */
397 WindowProcessController mPreviousProcess;
398 /** The time at which the previous process was last visible. */
399 long mPreviousProcessVisibleTime;
400
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700401 /** List of intents that were used to start the most recent tasks. */
402 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700403 /** State of external calls telling us if the device is awake or asleep. */
404 private boolean mKeyguardShown = false;
405
406 // Wrapper around VoiceInteractionServiceManager
407 private AssistUtils mAssistUtils;
408
409 // VoiceInteraction session ID that changes for each new request except when
410 // being called for multi-window assist in a single session.
411 private int mViSessionId = 1000;
412
413 // How long to wait in getAssistContextExtras for the activity and foreground services
414 // to respond with the result.
415 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
416
417 // How long top wait when going through the modern assist (which doesn't need to block
418 // on getting this result before starting to launch its UI).
419 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
420
421 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
422 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
423
Alison Cichowlas3e340502018-08-07 17:15:01 -0400424 // Permission tokens are used to temporarily granted a trusted app the ability to call
425 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
426 // showing any appropriate error messages to the user.
427 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
428 10 * MINUTE_IN_MILLIS;
429
430 // How long before the service actually expires a token. This is slightly longer than
431 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
432 // expiration exception.
433 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
434 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
435
436 // How long the service will remember expired tokens, for the purpose of providing error
437 // messaging when a client uses an expired token.
438 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
439 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
440
441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700467 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700554
555 /**
556 * Flag that indicates if multi-window is enabled.
557 *
558 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
559 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
560 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
561 * At least one of the forms of multi-window must be enabled in order for this flag to be
562 * initialized to 'true'.
563 *
564 * @see #mSupportsSplitScreenMultiWindow
565 * @see #mSupportsFreeformWindowManagement
566 * @see #mSupportsPictureInPicture
567 * @see #mSupportsMultiDisplay
568 */
569 boolean mSupportsMultiWindow;
570 boolean mSupportsSplitScreenMultiWindow;
571 boolean mSupportsFreeformWindowManagement;
572 boolean mSupportsPictureInPicture;
573 boolean mSupportsMultiDisplay;
574 boolean mForceResizableActivities;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700575 boolean mSizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
Riddle Hsua0022cd2019-09-09 21:12:41 +0800603 @Retention(RetentionPolicy.SOURCE)
604 @IntDef({
605 LAYOUT_REASON_CONFIG_CHANGED,
606 LAYOUT_REASON_VISIBILITY_CHANGED,
607 })
608 @interface LayoutReason {}
609 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
610 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
611
612 /** The reasons to perform surface placement. */
613 @LayoutReason
614 private int mLayoutReasons;
615
Wale Ogunwalef6733932018-06-27 05:14:34 -0700616 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
617 // automatically. Important for devices without direct input devices.
618 private boolean mShowDialogs = true;
619
620 /** Set if we are shutting down the system, similar to sleeping. */
621 boolean mShuttingDown = false;
622
623 /**
624 * We want to hold a wake lock while running a voice interaction session, since
625 * this may happen with the screen off and we need to keep the CPU running to
626 * be able to continue to interact with the user.
627 */
628 PowerManager.WakeLock mVoiceWakeLock;
629
630 /**
631 * Set while we are running a voice interaction. This overrides sleeping while it is active.
632 */
633 IVoiceInteractionSession mRunningVoice;
634
635 /**
636 * The last resumed activity. This is identical to the current resumed activity most
637 * of the time but could be different when we're pausing one activity before we resume
638 * another activity.
639 */
640 ActivityRecord mLastResumedActivity;
641
642 /**
643 * The activity that is currently being traced as the active resumed activity.
644 *
645 * @see #updateResumedAppTrace
646 */
647 private @Nullable ActivityRecord mTracedResumedActivity;
648
649 /** If non-null, we are tracking the time the user spends in the currently focused app. */
650 AppTimeTracker mCurAppTimeTracker;
651
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700652 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700653
Wale Ogunwale53783742018-09-16 10:21:51 -0700654 /**
655 * Packages that the user has asked to have run in screen size
656 * compatibility mode instead of filling the screen.
657 */
658 CompatModePackages mCompatModePackages;
659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private FontScaleSettingObserver mFontScaleSettingObserver;
661
Robert Carr8a2f9132019-11-11 15:03:15 -0800662 /**
663 * Stores the registration and state of TaskOrganizers in use.
664 */
Evan Rosky0037e5f2019-11-05 10:26:24 -0800665 TaskOrganizerController mTaskOrganizerController = new TaskOrganizerController(this);
Robert Carr8a2f9132019-11-11 15:03:15 -0800666
Ricky Wai96f5c352019-04-10 18:40:17 +0100667 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000668
Wale Ogunwalef6733932018-06-27 05:14:34 -0700669 private final class FontScaleSettingObserver extends ContentObserver {
670 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
671 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
672
673 public FontScaleSettingObserver() {
674 super(mH);
675 final ContentResolver resolver = mContext.getContentResolver();
676 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
677 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
678 UserHandle.USER_ALL);
679 }
680
681 @Override
682 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
683 if (mFontScaleUri.equals(uri)) {
684 updateFontScaleIfNeeded(userId);
685 } else if (mHideErrorDialogsUri.equals(uri)) {
686 synchronized (mGlobalLock) {
687 updateShouldShowDialogsLocked(getGlobalConfiguration());
688 }
689 }
690 }
691 }
692
Riddle Hsua0536432019-02-16 00:38:59 +0800693 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
694 @Target(ElementType.METHOD)
695 @Retention(RetentionPolicy.SOURCE)
696 @interface HotPath {
697 int NONE = 0;
698 int OOM_ADJUSTMENT = 1;
699 int LRU_UPDATE = 2;
700 int PROCESS_CHANGE = 3;
701 int caller() default NONE;
702 }
703
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800704 private final Runnable mUpdateOomAdjRunnable = new Runnable() {
705 @Override
Wale Ogunwale85fb19a2019-12-05 10:41:05 +0900706 public void run() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -0800707 mAmInternal.updateOomAdj();
708 }
709 };
710
Charles Chen8d98dd22018-12-26 17:36:54 +0800711 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
712 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700713 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700714 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700715 mSystemThread = ActivityThread.currentActivityThread();
716 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700717 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800718 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700719 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700720 }
721
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700722 public void onSystemReady() {
723 synchronized (mGlobalLock) {
724 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
725 PackageManager.FEATURE_CANT_SAVE_STATE);
726 mAssistUtils = new AssistUtils(mContext);
727 mVrController.onSystemReady();
728 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700729 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700730 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700731 }
732
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700733 public void onInitPowerManagement() {
734 synchronized (mGlobalLock) {
735 mStackSupervisor.initPowerManagement();
736 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
737 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
738 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
739 mVoiceWakeLock.setReferenceCounted(false);
740 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700741 }
742
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700743 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700744 mFontScaleSettingObserver = new FontScaleSettingObserver();
745 }
746
Wale Ogunwale59507092018-10-29 09:00:30 -0700747 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700748 final boolean freeformWindowManagement =
749 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
750 || Settings.Global.getInt(
751 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
752
753 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
754 final boolean supportsPictureInPicture = supportsMultiWindow &&
755 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
756 final boolean supportsSplitScreenMultiWindow =
757 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
758 final boolean supportsMultiDisplay = mContext.getPackageManager()
759 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700760 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
761 final boolean forceResizable = Settings.Global.getInt(
762 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700763 final boolean sizeCompatFreeform = Settings.Global.getInt(
764 resolver, DEVELOPMENT_ENABLE_SIZECOMPAT_FREEFORM, 0) != 0;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765
766 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900767 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768
769 final Configuration configuration = new Configuration();
770 Settings.System.getConfiguration(resolver, configuration);
771 if (forceRtl) {
772 // This will take care of setting the correct layout direction flags
773 configuration.setLayoutDirection(configuration.locale);
774 }
775
776 synchronized (mGlobalLock) {
777 mForceResizableActivities = forceResizable;
Shivam Agrawal780b5bb2019-07-17 10:17:11 -0700778 mSizeCompatFreeform = sizeCompatFreeform;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700779 final boolean multiWindowFormEnabled = freeformWindowManagement
780 || supportsSplitScreenMultiWindow
781 || supportsPictureInPicture
782 || supportsMultiDisplay;
783 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
784 mSupportsMultiWindow = true;
785 mSupportsFreeformWindowManagement = freeformWindowManagement;
786 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
787 mSupportsPictureInPicture = supportsPictureInPicture;
788 mSupportsMultiDisplay = supportsMultiDisplay;
789 } else {
790 mSupportsMultiWindow = false;
791 mSupportsFreeformWindowManagement = false;
792 mSupportsSplitScreenMultiWindow = false;
793 mSupportsPictureInPicture = false;
794 mSupportsMultiDisplay = false;
795 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700796 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700797 // This happens before any activities are started, so we can change global configuration
798 // in-place.
799 updateConfigurationLocked(configuration, null, true);
800 final Configuration globalConfig = getGlobalConfiguration();
801 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
802
803 // Load resources only after the current configuration has been set.
804 final Resources res = mContext.getResources();
805 mThumbnailWidth = res.getDimensionPixelSize(
806 com.android.internal.R.dimen.thumbnail_width);
807 mThumbnailHeight = res.getDimensionPixelSize(
808 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700809 }
810 }
811
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800812 public WindowManagerGlobalLock getGlobalLock() {
813 return mGlobalLock;
814 }
815
Yunfan Chen585f2932019-01-29 16:04:45 +0900816 /** For test purpose only. */
817 @VisibleForTesting
818 public ActivityTaskManagerInternal getAtmInternal() {
819 return mInternal;
820 }
821
Riddle Hsud93a6c42018-11-29 21:50:06 +0800822 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
823 Looper looper) {
824 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700826 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700827 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800828 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700829 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700830 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700831 mStackSupervisor = createStackSupervisor();
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700832
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700833 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700834 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700835 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700837 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700838 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700839 mKeyguardController = mStackSupervisor.getKeyguardController();
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void onActivityManagerInternalAdded() {
843 synchronized (mGlobalLock) {
844 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
845 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
846 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700847 }
848
Yunfan Chen75157d72018-07-27 14:47:21 +0900849 int increaseConfigurationSeqLocked() {
850 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
851 return mConfigurationSeq;
852 }
853
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700854 protected ActivityStackSupervisor createStackSupervisor() {
855 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
856 supervisor.initialize();
857 return supervisor;
858 }
859
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800860 protected AppWarnings createAppWarnings(
861 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
862 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
863 }
864
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700865 public void setWindowManager(WindowManagerService wm) {
866 synchronized (mGlobalLock) {
867 mWindowManager = wm;
Louis Chang149d5c82019-12-30 09:47:39 +0800868 mRootWindowContainer = wm.mRoot;
Louis Chang3ff72a82019-12-17 12:12:59 +0800869 mTempConfig.setToDefaults();
870 mTempConfig.setLocales(LocaleList.getDefault());
871 mConfigurationSeq = mTempConfig.seq = 1;
Louis Chang149d5c82019-12-30 09:47:39 +0800872 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700873 mLockTaskController.setWindowManager(wm);
874 mStackSupervisor.setWindowManager(wm);
Louis Chang149d5c82019-12-30 09:47:39 +0800875 mRootWindowContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700876 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700877 }
878
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700879 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
880 synchronized (mGlobalLock) {
881 mUsageStatsInternal = usageStatsManager;
882 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700883 }
884
Wale Ogunwalef6733932018-06-27 05:14:34 -0700885 UserManagerService getUserManager() {
886 if (mUserManager == null) {
887 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
888 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
889 }
890 return mUserManager;
891 }
892
Philip P. Moltmannee295092020-02-10 08:46:26 -0800893 AppOpsManager getAppOpsManager() {
894 if (mAppOpsManager == null) {
895 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Wale Ogunwalef6733932018-06-27 05:14:34 -0700896 }
Philip P. Moltmannee295092020-02-10 08:46:26 -0800897 return mAppOpsManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700898 }
899
900 boolean hasUserRestriction(String restriction, int userId) {
901 return getUserManager().hasUserRestriction(restriction, userId);
902 }
903
Michal Karpinski15486842019-04-25 17:33:42 +0100904 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
Philip P. Moltmannee295092020-02-10 08:46:26 -0800905 final int mode = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
906 callingUid, callingPackage, /* featureId */ null, "");
Michal Karpinski15486842019-04-25 17:33:42 +0100907 if (mode == AppOpsManager.MODE_DEFAULT) {
908 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
909 == PERMISSION_GRANTED;
910 }
911 return mode == AppOpsManager.MODE_ALLOWED;
912 }
913
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700914 @VisibleForTesting
915 protected void setRecentTasks(RecentTasks recentTasks) {
916 mRecentTasks = recentTasks;
917 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700918 }
919
920 RecentTasks getRecentTasks() {
921 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700922 }
923
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700924 ClientLifecycleManager getLifecycleManager() {
925 return mLifecycleManager;
926 }
927
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700928 ActivityStartController getActivityStartController() {
929 return mActivityStartController;
930 }
931
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700932 TaskChangeNotificationController getTaskChangeNotificationController() {
933 return mTaskChangeNotificationController;
934 }
935
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700936 LockTaskController getLockTaskController() {
937 return mLockTaskController;
938 }
939
Yunfan Chen75157d72018-07-27 14:47:21 +0900940 /**
941 * Return the global configuration used by the process corresponding to the input pid. This is
942 * usually the global configuration with some overrides specific to that process.
943 */
944 Configuration getGlobalConfigurationForCallingPid() {
945 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800946 return getGlobalConfigurationForPid(pid);
947 }
948
949 /**
950 * Return the global configuration used by the process corresponding to the given pid.
951 */
952 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900953 if (pid == MY_PID || pid < 0) {
954 return getGlobalConfiguration();
955 }
956 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100957 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900958 return app != null ? app.getConfiguration() : getGlobalConfiguration();
959 }
960 }
961
962 /**
963 * Return the device configuration info used by the process corresponding to the input pid.
964 * The value is consistent with the global configuration for the process.
965 */
966 @Override
967 public ConfigurationInfo getDeviceConfigurationInfo() {
968 ConfigurationInfo config = new ConfigurationInfo();
969 synchronized (mGlobalLock) {
970 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
971 config.reqTouchScreen = globalConfig.touchscreen;
972 config.reqKeyboardType = globalConfig.keyboard;
973 config.reqNavigation = globalConfig.navigation;
974 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
975 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
976 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
977 }
978 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
979 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
980 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
981 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700982 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900983 }
984 return config;
985 }
986
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700987 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700988 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700989 }
990
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700991 public static final class Lifecycle extends SystemService {
992 private final ActivityTaskManagerService mService;
993
994 public Lifecycle(Context context) {
995 super(context);
996 mService = new ActivityTaskManagerService(context);
997 }
998
999 @Override
1000 public void onStart() {
1001 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001002 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001003 }
1004
Garfield Tan891146c2018-10-09 12:14:00 -07001005 @Override
1006 public void onUnlockUser(int userId) {
1007 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -08001008 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -07001009 }
1010 }
1011
1012 @Override
1013 public void onCleanupUser(int userId) {
1014 synchronized (mService.getGlobalLock()) {
1015 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
1016 }
1017 }
1018
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001019 public ActivityTaskManagerService getService() {
1020 return mService;
1021 }
1022 }
1023
1024 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001025 public final int startActivity(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001026 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1027 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1028 Bundle bOptions) {
1029 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1030 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001031 UserHandle.getCallingUserId());
1032 }
1033
1034 @Override
1035 public final int startActivities(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001036 String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
1037 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001038 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001039 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001040 enforceNotIsolatedCaller(reason);
1041 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001043 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001044 callingFeatureId, intents, resolvedTypes, resultTo,
1045 SafeActivityOptions.fromBundle(bOptions), userId, reason,
1046 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001047 }
1048
1049 @Override
1050 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001051 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1052 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1053 Bundle bOptions, int userId) {
1054 return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
1055 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 true /*validateIncomingUser*/);
1057 }
1058
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001059 private int startActivityAsUser(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001060 @Nullable String callingFeatureId, Intent intent, String resolvedType,
1061 IBinder resultTo, String resultWho, int requestCode, int startFlags,
1062 ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001063 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001064 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001066 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001067 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1068
1069 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001070 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071 .setCaller(caller)
1072 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001073 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 .setResolvedType(resolvedType)
1075 .setResultTo(resultTo)
1076 .setResultWho(resultWho)
1077 .setRequestCode(requestCode)
1078 .setStartFlags(startFlags)
1079 .setProfilerInfo(profilerInfo)
1080 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001081 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 .execute();
1083
1084 }
1085
1086 @Override
1087 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1088 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001089 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1090 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 // Refuse possible leaked file descriptors
1092 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1093 throw new IllegalArgumentException("File descriptors passed in Intent");
1094 }
1095
1096 if (!(target instanceof PendingIntentRecord)) {
1097 throw new IllegalArgumentException("Bad PendingIntent object");
1098 }
1099
1100 PendingIntentRecord pir = (PendingIntentRecord)target;
1101
1102 synchronized (mGlobalLock) {
1103 // If this is coming from the currently resumed activity, it is
1104 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001105 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001106 if (stack.mResumedActivity != null &&
1107 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001108 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001109 }
1110 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001111 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 }
1114
1115 @Override
1116 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1117 Bundle bOptions) {
1118 // Refuse possible leaked file descriptors
1119 if (intent != null && intent.hasFileDescriptors()) {
1120 throw new IllegalArgumentException("File descriptors passed in Intent");
1121 }
1122 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1123
1124 synchronized (mGlobalLock) {
1125 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1126 if (r == null) {
1127 SafeActivityOptions.abort(options);
1128 return false;
1129 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001130 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001131 // The caller is not running... d'oh!
1132 SafeActivityOptions.abort(options);
1133 return false;
1134 }
1135 intent = new Intent(intent);
1136 // The caller is not allowed to change the data.
1137 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1138 // And we are resetting to find the next component...
1139 intent.setComponent(null);
1140
1141 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1142
1143 ActivityInfo aInfo = null;
1144 try {
1145 List<ResolveInfo> resolves =
1146 AppGlobals.getPackageManager().queryIntentActivities(
1147 intent, r.resolvedType,
1148 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1149 UserHandle.getCallingUserId()).getList();
1150
1151 // Look for the original activity in the list...
1152 final int N = resolves != null ? resolves.size() : 0;
1153 for (int i=0; i<N; i++) {
1154 ResolveInfo rInfo = resolves.get(i);
1155 if (rInfo.activityInfo.packageName.equals(r.packageName)
1156 && rInfo.activityInfo.name.equals(r.info.name)) {
1157 // We found the current one... the next matching is
1158 // after it.
1159 i++;
1160 if (i<N) {
1161 aInfo = resolves.get(i).activityInfo;
1162 }
1163 if (debug) {
1164 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1165 + "/" + r.info.name);
1166 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1167 ? "null" : aInfo.packageName + "/" + aInfo.name));
1168 }
1169 break;
1170 }
1171 }
1172 } catch (RemoteException e) {
1173 }
1174
1175 if (aInfo == null) {
1176 // Nobody who is next!
1177 SafeActivityOptions.abort(options);
1178 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1179 return false;
1180 }
1181
1182 intent.setComponent(new ComponentName(
1183 aInfo.applicationInfo.packageName, aInfo.name));
1184 intent.setFlags(intent.getFlags()&~(
1185 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1186 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1187 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1188 FLAG_ACTIVITY_NEW_TASK));
1189
1190 // Okay now we need to start the new activity, replacing the currently running activity.
1191 // This is a little tricky because we want to start the new one as if the current one is
1192 // finished, but not finish the current one first so that there is no flicker.
1193 // And thus...
1194 final boolean wasFinishing = r.finishing;
1195 r.finishing = true;
1196
1197 // Propagate reply information over to the new activity.
1198 final ActivityRecord resultTo = r.resultTo;
1199 final String resultWho = r.resultWho;
1200 final int requestCode = r.requestCode;
1201 r.resultTo = null;
1202 if (resultTo != null) {
1203 resultTo.removeResultsLocked(r, resultWho, requestCode);
1204 }
1205
1206 final long origId = Binder.clearCallingIdentity();
1207 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001208 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001210 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 .setResolvedType(r.resolvedType)
1212 .setActivityInfo(aInfo)
1213 .setResultTo(resultTo != null ? resultTo.appToken : null)
1214 .setResultWho(resultWho)
1215 .setRequestCode(requestCode)
1216 .setCallingPid(-1)
1217 .setCallingUid(r.launchedFromUid)
1218 .setCallingPackage(r.launchedFromPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001219 .setCallingFeatureId(r.launchedFromFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 .setRealCallingPid(-1)
1221 .setRealCallingUid(r.launchedFromUid)
1222 .setActivityOptions(options)
1223 .execute();
1224 Binder.restoreCallingIdentity(origId);
1225
1226 r.finishing = wasFinishing;
1227 if (res != ActivityManager.START_SUCCESS) {
1228 return false;
1229 }
1230 return true;
1231 }
1232 }
1233
1234 @Override
Galia Peycheva6861e912019-08-21 10:20:23 +02001235 public boolean startDreamActivity(Intent intent) {
1236 final ActivityInfo a = new ActivityInfo();
1237 a.theme = com.android.internal.R.style.Theme_Dream;
1238 a.exported = true;
1239 a.name = DreamActivity.class.getName();
1240
1241 final WindowProcessController process = mProcessMap.getProcess(Binder.getCallingPid());
1242
1243 a.packageName = process.mInfo.packageName;
1244 a.applicationInfo = process.mInfo;
1245 a.processName = process.mInfo.processName;
1246 a.uiOptions = process.mInfo.uiOptions;
1247 a.taskAffinity = "android:" + a.packageName + "/dream";
1248 a.enabled = true;
1249 a.launchMode = ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1250
1251 a.persistableMode = ActivityInfo.PERSIST_NEVER;
1252 a.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1253 a.colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
1254 a.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1255
1256 final long origId = Binder.clearCallingIdentity();
1257 try {
1258 getActivityStartController().obtainStarter(intent, "dream")
1259 .setActivityInfo(a)
1260 .setIsDream(true)
1261 .execute();
1262 return true;
1263 } finally {
1264 Binder.restoreCallingIdentity(origId);
1265 }
1266 }
1267
1268 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001269 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001270 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1271 String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
1272 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001273 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 final WaitResult res = new WaitResult();
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001275 enforceNotIsolatedCaller("startActivityAndWait");
1276 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1277 userId, "startActivityAndWait");
1278 // TODO: Switch to user app stacks here.
1279 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
1280 .setCaller(caller)
1281 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001282 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001283 .setResolvedType(resolvedType)
1284 .setResultTo(resultTo)
1285 .setResultWho(resultWho)
1286 .setRequestCode(requestCode)
1287 .setStartFlags(startFlags)
1288 .setActivityOptions(bOptions)
1289 .setUserId(userId)
1290 .setProfilerInfo(profilerInfo)
1291 .setWaitResult(res)
1292 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 return res;
1294 }
1295
1296 @Override
1297 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001298 String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
1299 String resultWho, int requestCode, int startFlags, Configuration config,
1300 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001301 assertPackageMatchesCallingUid(callingPackage);
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001302 enforceNotIsolatedCaller("startActivityWithConfig");
1303 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1304 "startActivityWithConfig");
1305 // TODO: Switch to user app stacks here.
1306 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
1307 .setCaller(caller)
1308 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001309 .setCallingFeatureId(callingFeatureId)
Riddle Hsufd66d4d2019-11-14 10:35:55 +08001310 .setResolvedType(resolvedType)
1311 .setResultTo(resultTo)
1312 .setResultWho(resultWho)
1313 .setRequestCode(requestCode)
1314 .setStartFlags(startFlags)
1315 .setGlobalConfiguration(config)
1316 .setActivityOptions(bOptions)
1317 .setUserId(userId)
1318 .execute();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 }
1320
Robert Carr8a2f9132019-11-11 15:03:15 -08001321 @Override
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1323 int callingUid = Binder.getCallingUid();
1324 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1325 throw new SecurityException("Only the system process can request a permission token, "
1326 + "received request from uid: " + callingUid);
1327 }
1328 IBinder permissionToken = new Binder();
1329 synchronized (mGlobalLock) {
1330 mStartActivitySources.put(permissionToken, delegatorToken);
1331 }
1332
1333 Message expireMsg = PooledLambda.obtainMessage(
1334 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1335 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1336
1337 Message forgetMsg = PooledLambda.obtainMessage(
1338 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1339 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1340
1341 return permissionToken;
1342 }
1343
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 @Override
1345 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1346 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001347 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1348 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001350 // permission grants) as any app that may launch one of your own activities. So we only
1351 // allow this in two cases:
1352 // 1) The caller is an activity that is part of the core framework, and then only when it
1353 // is running as the system.
1354 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1355 // can only be requested by a system activity, which may then delegate this call to
1356 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 final ActivityRecord sourceRecord;
1358 final int targetUid;
1359 final String targetPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001360 final String targetFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 final boolean isResolver;
1362 synchronized (mGlobalLock) {
1363 if (resultTo == null) {
1364 throw new SecurityException("Must be called from an activity");
1365 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001366 final IBinder sourceToken;
1367 if (permissionToken != null) {
1368 // To even attempt to use a permissionToken, an app must also have this signature
1369 // permission.
1370 mAmInternal.enforceCallingPermission(
1371 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1372 "startActivityAsCaller");
1373 // If called with a permissionToken, we want the sourceRecord from the delegator
1374 // activity that requested this token.
1375 sourceToken = mStartActivitySources.remove(permissionToken);
1376 if (sourceToken == null) {
1377 // Invalid permissionToken, check if it recently expired.
1378 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1379 throw new SecurityException("Called with expired permission token: "
1380 + permissionToken);
1381 } else {
1382 throw new SecurityException("Called with invalid permission token: "
1383 + permissionToken);
1384 }
1385 }
1386 } else {
1387 // This method was called directly by the source.
1388 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001390
Louis Chang149d5c82019-12-30 09:47:39 +08001391 sourceRecord = mRootWindowContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001392 if (sourceRecord == null) {
1393 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001394 }
1395 if (sourceRecord.app == null) {
1396 throw new SecurityException("Called without a process attached to activity");
1397 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001398
1399 // Whether called directly or from a delegate, the source activity must be from the
1400 // android package.
1401 if (!sourceRecord.info.packageName.equals("android")) {
1402 throw new SecurityException("Must be called from an activity that is "
1403 + "declared in the android package");
1404 }
1405
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001406 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 // This is still okay, as long as this activity is running under the
1408 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001409 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001410 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001411 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 + " must be system uid or original calling uid "
1413 + sourceRecord.launchedFromUid);
1414 }
1415 }
1416 if (ignoreTargetSecurity) {
1417 if (intent.getComponent() == null) {
1418 throw new SecurityException(
1419 "Component must be specified with ignoreTargetSecurity");
1420 }
1421 if (intent.getSelector() != null) {
1422 throw new SecurityException(
1423 "Selector not allowed with ignoreTargetSecurity");
1424 }
1425 }
1426 targetUid = sourceRecord.launchedFromUid;
1427 targetPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -08001428 targetFeatureId = sourceRecord.launchedFromFeatureId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 isResolver = sourceRecord.isResolverOrChildActivity();
1430 }
1431
1432 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001433 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434 }
1435
1436 // TODO: Switch to user app stacks here.
1437 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001438 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 .setCallingUid(targetUid)
1440 .setCallingPackage(targetPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001441 .setCallingFeatureId(targetFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001442 .setResolvedType(resolvedType)
1443 .setResultTo(resultTo)
1444 .setResultWho(resultWho)
1445 .setRequestCode(requestCode)
1446 .setStartFlags(startFlags)
1447 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001448 .setUserId(userId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1450 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001451 // The target may well be in the background, which would normally prevent it
1452 // from starting an activity. Here we definitely want the start to succeed.
1453 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 .execute();
1455 } catch (SecurityException e) {
1456 // XXX need to figure out how to propagate to original app.
1457 // A SecurityException here is generally actually a fault of the original
1458 // calling activity (such as a fairly granting permissions), so propagate it
1459 // back to them.
1460 /*
1461 StringBuilder msg = new StringBuilder();
1462 msg.append("While launching");
1463 msg.append(intent.toString());
1464 msg.append(": ");
1465 msg.append(e.getMessage());
1466 */
1467 throw e;
1468 }
1469 }
1470
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001471 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1472 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
Jonathan Scott92335342019-12-17 14:46:26 +00001473 ALLOW_NON_FULL, name, null /* callerPackage */);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001474 }
1475
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001476 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001477 public int startVoiceActivity(String callingPackage, String callingFeatureId, int callingPid,
1478 int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001479 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1480 Bundle bOptions, int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001481 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001482 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 if (session == null || interactor == null) {
1484 throw new NullPointerException("null session or interactor");
1485 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001486 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001487 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001488 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 .setCallingUid(callingUid)
1490 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001491 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 .setResolvedType(resolvedType)
1493 .setVoiceSession(session)
1494 .setVoiceInteractor(interactor)
1495 .setStartFlags(startFlags)
1496 .setProfilerInfo(profilerInfo)
1497 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001498 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001499 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001500 .execute();
1501 }
1502
1503 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08001504 public int startAssistantActivity(String callingPackage, @NonNull String callingFeatureId,
1505 int callingPid, int callingUid, Intent intent, String resolvedType, Bundle bOptions,
1506 int userId) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07001507 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1509 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001511 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001512 .setCallingUid(callingUid)
1513 .setCallingPackage(callingPackage)
Philip P. Moltmannee295092020-02-10 08:46:26 -08001514 .setCallingFeatureId(callingFeatureId)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001515 .setResolvedType(resolvedType)
1516 .setActivityOptions(bOptions)
Louis Chang54fbb052019-10-16 17:10:17 +08001517 .setUserId(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001518 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001519 .execute();
1520 }
1521
Riddle Hsu609a8e22019-06-27 16:46:29 -06001522 /**
1523 * Start the recents activity to perform the recents animation.
1524 *
1525 * @param intent The intent to start the recents activity.
1526 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1527 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001529 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1530 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001531 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001532 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001533 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001534 final long origId = Binder.clearCallingIdentity();
1535 try {
1536 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001537 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
Philip P. Moltmannee295092020-02-10 08:46:26 -08001538 final String recentsFeatureId = mRecentTasks.getRecentsComponentFeatureId();
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001539 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001540 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541
1542 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001543 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001544 getActivityStartController(), mWindowManager, intent, recentsComponent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001545 recentsFeatureId, recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001546 if (recentsAnimationRunner == null) {
1547 anim.preloadRecentsActivity();
1548 } else {
1549 anim.startRecentsActivity(recentsAnimationRunner);
1550 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 }
1552 } finally {
1553 Binder.restoreCallingIdentity(origId);
1554 }
1555 }
1556
1557 @Override
1558 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001559 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 "startActivityFromRecents()");
1561
1562 final int callingPid = Binder.getCallingPid();
1563 final int callingUid = Binder.getCallingUid();
1564 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1565 final long origId = Binder.clearCallingIdentity();
1566 try {
1567 synchronized (mGlobalLock) {
1568 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1569 safeOptions);
1570 }
1571 } finally {
1572 Binder.restoreCallingIdentity(origId);
1573 }
1574 }
1575
1576 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001577 * Public API to check if the client is allowed to start an activity on specified display.
1578 *
1579 * If the target display is private or virtual, some restrictions will apply.
1580 *
1581 * @param displayId Target display id.
1582 * @param intent Intent used to launch the activity.
1583 * @param resolvedType The MIME type of the intent.
1584 * @param userId The id of the user for whom the call is made.
1585 * @return {@code true} if a call to start an activity on the target display should succeed and
1586 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1587 */
1588 @Override
1589 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1590 String resolvedType, int userId) {
1591 final int callingUid = Binder.getCallingUid();
1592 final int callingPid = Binder.getCallingPid();
1593 final long origId = Binder.clearCallingIdentity();
1594
1595 try {
1596 // Collect information about the target of the Intent.
1597 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1598 0 /* startFlags */, null /* profilerInfo */, userId,
1599 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1600 UserHandle.USER_NULL));
1601 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1602
1603 synchronized (mGlobalLock) {
1604 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1605 aInfo);
1606 }
1607 } finally {
1608 Binder.restoreCallingIdentity(origId);
1609 }
1610 }
1611
1612 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 * This is the internal entry point for handling Activity.finish().
1614 *
1615 * @param token The Binder token referencing the Activity we want to finish.
1616 * @param resultCode Result code, if any, from this Activity.
1617 * @param resultData Result data (Intent), if any, from this Activity.
1618 * @param finishTask Whether to finish the task associated with this Activity.
1619 *
1620 * @return Returns true if the activity successfully finished, or false if it is still running.
1621 */
1622 @Override
1623 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1624 int finishTask) {
1625 // Refuse possible leaked file descriptors
1626 if (resultData != null && resultData.hasFileDescriptors()) {
1627 throw new IllegalArgumentException("File descriptors passed in Intent");
1628 }
1629
1630 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001631 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 if (r == null) {
1633 return true;
1634 }
1635 // Keep track of the root activity of the task before we finish it
Louis Changcdec0802019-11-11 11:45:07 +08001636 final Task tr = r.getTask();
Andrii Kulian057a6512019-07-15 16:15:51 -07001637 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001638 if (rootR == null) {
1639 Slog.w(TAG, "Finishing task with all activities already finished");
1640 }
1641 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1642 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001643 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 return false;
1645 }
1646
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001647 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1648 // We should consolidate.
1649 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 // Find the first activity that is not finishing.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001651 final ActivityRecord next =
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001652 r.getRootTask().topRunningActivity(token, INVALID_TASK_ID);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 if (next != null) {
1654 // ask watcher if this is allowed
1655 boolean resumeOK = true;
1656 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001657 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001659 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001660 Watchdog.getInstance().setActivityController(null);
1661 }
1662
1663 if (!resumeOK) {
1664 Slog.i(TAG, "Not finishing activity because controller resumed");
1665 return false;
1666 }
1667 }
1668 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001669
1670 // note down that the process has finished an activity and is in background activity
1671 // starts grace period
1672 if (r.app != null) {
1673 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1674 }
1675
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001677 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "finishActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 try {
1679 boolean res;
1680 final boolean finishWithRootActivity =
1681 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1682 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1683 || (finishWithRootActivity && r == rootR)) {
1684 // If requested, remove the task that is associated to this activity only if it
1685 // was the root activity in the task. The result code and data is ignored
1686 // because we don't support returning them across task boundaries. Also, to
1687 // keep backwards compatibility we remove the task from recents when finishing
1688 // task with root activity.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001689 mStackSupervisor.removeTask(tr, false /*killProcess*/,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 finishWithRootActivity, "finish-activity");
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001691 res = true;
Garfield Tan2746ab52018-07-25 12:33:01 -07001692 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001693 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001694 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001695 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001696 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 if (!res) {
1698 Slog.i(TAG, "Failed to finish by app-request");
1699 }
1700 }
1701 return res;
1702 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001703 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001704 Binder.restoreCallingIdentity(origId);
1705 }
1706 }
1707 }
1708
1709 @Override
1710 public boolean finishActivityAffinity(IBinder token) {
1711 synchronized (mGlobalLock) {
1712 final long origId = Binder.clearCallingIdentity();
1713 try {
1714 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1715 if (r == null) {
1716 return false;
1717 }
1718
1719 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1720 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001721 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001722 return false;
1723 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001724
1725 final PooledFunction p = PooledLambda.obtainFunction(
1726 ActivityRecord::finishIfSameAffinity, r,
1727 PooledLambda.__(ActivityRecord.class));
1728 r.getTask().forAllActivities(
1729 p, r, true /*includeBoundary*/, true /*traverseTopToBottom*/);
1730 p.recycle();
1731
Andrii Kuliande93eff2019-07-12 12:21:27 -07001732 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 } finally {
1734 Binder.restoreCallingIdentity(origId);
1735 }
1736 }
1737 }
1738
1739 @Override
1740 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1741 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001742 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001743 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001744 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle");
Riddle Hsufc8ab262019-12-31 15:31:24 +08001745 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1746 if (r == null) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001747 return;
1748 }
Riddle Hsufc8ab262019-12-31 15:31:24 +08001749 mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
1750 false /* processPausingActivities */, config);
1751 if (stopProfiling && r.hasProcess()) {
1752 r.app.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 }
1754 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001755 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001756 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001757 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 }
1760
1761 @Override
1762 public final void activityResumed(IBinder token) {
1763 final long origId = Binder.clearCallingIdentity();
1764 synchronized (mGlobalLock) {
1765 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 }
1767 Binder.restoreCallingIdentity(origId);
1768 }
1769
1770 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001771 public final void activityTopResumedStateLost() {
1772 final long origId = Binder.clearCallingIdentity();
1773 synchronized (mGlobalLock) {
1774 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1775 }
1776 Binder.restoreCallingIdentity(origId);
1777 }
1778
1779 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001780 public final void activityPaused(IBinder token) {
1781 final long origId = Binder.clearCallingIdentity();
1782 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001783 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityPaused");
Wale Ogunwale196db712019-12-27 15:35:39 +00001784 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1785 if (r != null) {
1786 r.activityPaused(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001788 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001789 }
1790 Binder.restoreCallingIdentity(origId);
1791 }
1792
1793 @Override
1794 public final void activityStopped(IBinder token, Bundle icicle,
1795 PersistableBundle persistentState, CharSequence description) {
1796 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1797
1798 // Refuse possible leaked file descriptors
1799 if (icicle != null && icicle.hasFileDescriptors()) {
1800 throw new IllegalArgumentException("File descriptors passed in Bundle");
1801 }
1802
1803 final long origId = Binder.clearCallingIdentity();
1804
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001805 String restartingName = null;
1806 int restartingUid = 0;
1807 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001808 synchronized (mGlobalLock) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001809 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityStopped");
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001810 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001811 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001812 if (r.attachedToProcess()
1813 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1814 // The activity was requested to restart from
1815 // {@link #restartActivityProcessIfVisible}.
1816 restartingName = r.app.mName;
1817 restartingUid = r.app.mUid;
1818 }
Wale Ogunwale196db712019-12-27 15:35:39 +00001819 r.activityStopped(icicle, persistentState, description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001820 }
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001821 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001822 }
1823
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001824 if (restartingName != null) {
1825 // In order to let the foreground activity can be restarted with its saved state from
1826 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1827 // until the activity reports stopped with the state. And the activity record will be
1828 // kept because the record state is restarting, then the activity will be restarted
1829 // immediately if it is still the top one.
1830 mStackSupervisor.removeRestartTimeouts(r);
1831 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1832 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001833 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834
1835 Binder.restoreCallingIdentity(origId);
1836 }
1837
1838 @Override
1839 public final void activityDestroyed(IBinder token) {
1840 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1841 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001842 final long origId = Binder.clearCallingIdentity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001843 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityDestroyed");
Andrii Kulian79d67982019-08-19 11:56:16 -07001844 try {
1845 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1846 if (activity != null) {
1847 activity.destroyed("activityDestroyed");
1848 }
1849 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001850 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Andrii Kulian79d67982019-08-19 11:56:16 -07001851 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001852 }
1853 }
1854 }
1855
1856 @Override
1857 public final void activityRelaunched(IBinder token) {
1858 final long origId = Binder.clearCallingIdentity();
1859 synchronized (mGlobalLock) {
1860 mStackSupervisor.activityRelaunchedLocked(token);
1861 }
1862 Binder.restoreCallingIdentity(origId);
1863 }
1864
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 @Override
1866 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1867 synchronized (mGlobalLock) {
1868 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1869 if (r == null) {
1870 return;
1871 }
1872 final long origId = Binder.clearCallingIdentity();
1873 try {
1874 r.setRequestedOrientation(requestedOrientation);
1875 } finally {
1876 Binder.restoreCallingIdentity(origId);
1877 }
1878 }
1879 }
1880
1881 @Override
1882 public int getRequestedOrientation(IBinder token) {
1883 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001884 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1885 return (r != null)
1886 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001887 }
1888 }
1889
1890 @Override
1891 public void setImmersive(IBinder token, boolean immersive) {
1892 synchronized (mGlobalLock) {
1893 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1894 if (r == null) {
1895 throw new IllegalArgumentException();
1896 }
1897 r.immersive = immersive;
1898
1899 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001900 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001902 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001903 }
1904 }
1905 }
1906
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001907 void applyUpdateLockStateLocked(ActivityRecord r) {
1908 // Modifications to the UpdateLock state are done on our handler, outside
1909 // the activity manager's locks. The new state is determined based on the
1910 // state *now* of the relevant activity record. The object is passed to
1911 // the handler solely for logging detail, not to be consulted/modified.
1912 final boolean nextState = r != null && r.immersive;
1913 mH.post(() -> {
1914 if (mUpdateLock.isHeld() != nextState) {
1915 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1916 "Applying new update lock state '" + nextState + "' for " + r);
1917 if (nextState) {
1918 mUpdateLock.acquire();
1919 } else {
1920 mUpdateLock.release();
1921 }
1922 }
1923 });
1924 }
1925
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 @Override
1927 public boolean isImmersive(IBinder token) {
1928 synchronized (mGlobalLock) {
1929 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1930 if (r == null) {
1931 throw new IllegalArgumentException();
1932 }
1933 return r.immersive;
1934 }
1935 }
1936
1937 @Override
1938 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001941 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 return (r != null) ? r.immersive : false;
1943 }
1944 }
1945
1946 @Override
1947 public void overridePendingTransition(IBinder token, String packageName,
1948 int enterAnim, int exitAnim) {
1949 synchronized (mGlobalLock) {
1950 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1951 if (self == null) {
1952 return;
1953 }
1954
1955 final long origId = Binder.clearCallingIdentity();
1956
1957 if (self.isState(
1958 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001959 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001960 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 }
1962
1963 Binder.restoreCallingIdentity(origId);
1964 }
1965 }
1966
1967 @Override
1968 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001969 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001970 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001971 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001972 if (r == null) {
1973 return ActivityManager.COMPAT_MODE_UNKNOWN;
1974 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001975 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001976 }
1977 }
1978
1979 @Override
1980 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001981 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001983 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001984 synchronized (mGlobalLock) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001985 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001986 if (r == null) {
1987 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1988 return;
1989 }
1990 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001991 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 }
1993 }
1994
1995 @Override
1996 public int getLaunchedFromUid(IBinder activityToken) {
1997 ActivityRecord srec;
1998 synchronized (mGlobalLock) {
1999 srec = ActivityRecord.forTokenLocked(activityToken);
2000 }
2001 if (srec == null) {
2002 return -1;
2003 }
2004 return srec.launchedFromUid;
2005 }
2006
2007 @Override
2008 public String getLaunchedFromPackage(IBinder activityToken) {
2009 ActivityRecord srec;
2010 synchronized (mGlobalLock) {
2011 srec = ActivityRecord.forTokenLocked(activityToken);
2012 }
2013 if (srec == null) {
2014 return null;
2015 }
2016 return srec.launchedFromPackage;
2017 }
2018
2019 @Override
2020 public boolean convertFromTranslucent(IBinder token) {
2021 final long origId = Binder.clearCallingIdentity();
2022 try {
2023 synchronized (mGlobalLock) {
2024 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2025 if (r == null) {
2026 return false;
2027 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002028 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 }
2030 } finally {
2031 Binder.restoreCallingIdentity(origId);
2032 }
2033 }
2034
2035 @Override
2036 public boolean convertToTranslucent(IBinder token, Bundle options) {
2037 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
2038 final long origId = Binder.clearCallingIdentity();
2039 try {
2040 synchronized (mGlobalLock) {
2041 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2042 if (r == null) {
2043 return false;
2044 }
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002045 final ActivityRecord under = r.getTask().getActivityBelow(r);
2046 if (under != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
2048 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002049 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 }
2051 } finally {
2052 Binder.restoreCallingIdentity(origId);
2053 }
2054 }
2055
2056 @Override
2057 public void notifyActivityDrawn(IBinder token) {
2058 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2059 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002060 ActivityRecord r = mRootWindowContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002061 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002062 r.getRootTask().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 }
2065 }
2066
2067 @Override
2068 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2069 synchronized (mGlobalLock) {
2070 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2071 if (r == null) {
2072 return;
2073 }
2074 r.reportFullyDrawnLocked(restoredFromBundle);
2075 }
2076 }
2077
2078 @Override
Louis Chang677921f2019-12-06 16:44:24 +08002079 public int getDisplayId(IBinder activityToken) throws RemoteException {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 synchronized (mGlobalLock) {
2081 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
Wale Ogunwale8f93b642019-12-26 12:10:52 -08002082 if (stack != null) {
2083 final int displayId = stack.getDisplayId();
2084 return displayId != INVALID_DISPLAY ? displayId : DEFAULT_DISPLAY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 return DEFAULT_DISPLAY;
2087 }
2088 }
2089
2090 @Override
2091 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002092 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002093 long ident = Binder.clearCallingIdentity();
2094 try {
2095 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002096 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 if (focusedStack != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002098 return mRootWindowContainer.getStackInfo(focusedStack.mTaskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 }
2100 return null;
2101 }
2102 } finally {
2103 Binder.restoreCallingIdentity(ident);
2104 }
2105 }
2106
2107 @Override
2108 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002109 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2111 final long callingId = Binder.clearCallingIdentity();
2112 try {
2113 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002114 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002115 if (stack == null) {
2116 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2117 return;
2118 }
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002119 final ActivityRecord r = stack.topRunningActivity();
Louis Chang19443452018-10-09 12:10:21 +08002120 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002121 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002122 }
2123 }
2124 } finally {
2125 Binder.restoreCallingIdentity(callingId);
2126 }
2127 }
2128
2129 @Override
2130 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002131 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002132 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2133 final long callingId = Binder.clearCallingIdentity();
2134 try {
2135 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002136 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002137 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 if (task == null) {
2139 return;
2140 }
2141 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002142 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Louis Chang149d5c82019-12-30 09:47:39 +08002143 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002144 }
2145 }
2146 } finally {
2147 Binder.restoreCallingIdentity(callingId);
2148 }
2149 }
2150
2151 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002152 public void restartActivityProcessIfVisible(IBinder activityToken) {
2153 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2154 final long callingId = Binder.clearCallingIdentity();
2155 try {
2156 synchronized (mGlobalLock) {
2157 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2158 if (r == null) {
2159 return;
2160 }
2161 r.restartProcessIfVisible();
2162 }
2163 } finally {
2164 Binder.restoreCallingIdentity(callingId);
2165 }
2166 }
2167
2168 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002169 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002170 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002171 synchronized (mGlobalLock) {
2172 final long ident = Binder.clearCallingIdentity();
2173 try {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002174 return mStackSupervisor.removeTaskById(taskId, true, REMOVE_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 "remove-task");
2176 } finally {
2177 Binder.restoreCallingIdentity(ident);
2178 }
2179 }
2180 }
2181
2182 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002183 public void removeAllVisibleRecentTasks() {
2184 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2185 synchronized (mGlobalLock) {
2186 final long ident = Binder.clearCallingIdentity();
2187 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002188 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002189 } finally {
2190 Binder.restoreCallingIdentity(ident);
2191 }
2192 }
2193 }
2194
2195 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002196 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2197 synchronized (mGlobalLock) {
2198 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2199 if (srec != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002200 return srec.getRootTask().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 }
2202 }
2203 return false;
2204 }
2205
2206 @Override
2207 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2208 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002209
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002210 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002211 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2212 if (r != null) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002213 return r.getRootTask().navigateUpTo(
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002214 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002215 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002216 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002217 }
2218 }
2219
2220 /**
2221 * Attempts to move a task backwards in z-order (the order of activities within the task is
2222 * unchanged).
2223 *
2224 * There are several possible results of this call:
2225 * - if the task is locked, then we will show the lock toast
2226 * - if there is a task behind the provided task, then that task is made visible and resumed as
2227 * this task is moved to the back
2228 * - otherwise, if there are no other tasks in the stack:
2229 * - if this task is in the pinned stack, then we remove the stack completely, which will
2230 * have the effect of moving the task to the top or bottom of the fullscreen stack
2231 * (depending on whether it is visible)
2232 * - otherwise, we simply return home and hide this task
2233 *
2234 * @param token A reference to the activity we wish to move
2235 * @param nonRoot If false then this only works if the activity is the root
2236 * of a task; if true it will work for any activity in a task.
2237 * @return Returns true if the move completed, false if not.
2238 */
2239 @Override
2240 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002241 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002242 synchronized (mGlobalLock) {
2243 final long origId = Binder.clearCallingIdentity();
2244 try {
2245 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Louis Chang149d5c82019-12-30 09:47:39 +08002246 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 if (task != null) {
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002248 return ActivityRecord.getStackLocked(token).moveTaskToBack(task);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002249 }
2250 } finally {
2251 Binder.restoreCallingIdentity(origId);
2252 }
2253 }
2254 return false;
2255 }
2256
2257 @Override
2258 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002260 long ident = Binder.clearCallingIdentity();
2261 Rect rect = new Rect();
2262 try {
2263 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002264 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002265 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2266 if (task == null) {
2267 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2268 return rect;
2269 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002270 if (task.getParent() != null) {
2271 rect.set(task.getBounds());
2272 } else if (task.mLastNonFullscreenBounds != null) {
2273 rect.set(task.mLastNonFullscreenBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002274 }
2275 }
2276 } finally {
2277 Binder.restoreCallingIdentity(ident);
2278 }
2279 return rect;
2280 }
2281
2282 @Override
2283 public ActivityManager.TaskDescription getTaskDescription(int id) {
2284 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Louis Chang149d5c82019-12-30 09:47:39 +08002287 final Task tr = mRootWindowContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002288 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2289 if (tr != null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02002290 return tr.getTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002291 }
2292 }
2293 return null;
2294 }
2295
2296 @Override
Winson Chung7ccc6812020-01-23 16:15:10 -08002297 public boolean setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002298 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
Winson Chung7ccc6812020-01-23 16:15:10 -08002299 return setTaskWindowingModeSplitScreenPrimary(taskId,
2300 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002301 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002302 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002303 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002304 synchronized (mGlobalLock) {
2305 final long ident = Binder.clearCallingIdentity();
2306 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002307 if (WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2308 return setTaskWindowingModeSplitScreen(taskId, windowingMode, toTop);
2309 }
Louis Chang149d5c82019-12-30 09:47:39 +08002310 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002311 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002312 if (task == null) {
2313 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
Winson Chung7ccc6812020-01-23 16:15:10 -08002314 return false;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002315 }
2316
2317 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2318 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2319
2320 if (!task.isActivityTypeStandardOrUndefined()) {
2321 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2322 + " non-standard task " + taskId + " to windowing mode="
2323 + windowingMode);
2324 }
2325
2326 final ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002327 // Convert some windowing-mode changes into root-task reparents for split-screen.
2328 if (stack.getTile() != null) {
2329 stack.getDisplay().onSplitScreenModeDismissed();
2330 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002331 if (toTop) {
2332 stack.moveToFront("setTaskWindowingMode", task);
2333 }
2334 stack.setWindowingMode(windowingMode);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002335 stack.getDisplay().ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS,
2336 true /* notifyClients */);
Winson Chung7ccc6812020-01-23 16:15:10 -08002337 return true;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002338 } finally {
2339 Binder.restoreCallingIdentity(ident);
2340 }
2341 }
2342 }
2343
2344 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002346 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002347 ActivityRecord r = getCallingRecordLocked(token);
2348 return r != null ? r.info.packageName : null;
2349 }
2350 }
2351
2352 @Override
2353 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002354 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 ActivityRecord r = getCallingRecordLocked(token);
2356 return r != null ? r.intent.getComponent() : null;
2357 }
2358 }
2359
2360 private ActivityRecord getCallingRecordLocked(IBinder token) {
2361 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2362 if (r == null) {
2363 return null;
2364 }
2365 return r.resultTo;
2366 }
2367
2368 @Override
2369 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002370 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002371
2372 synchronized (mGlobalLock) {
2373 final long origId = Binder.clearCallingIdentity();
2374 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002375 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 } finally {
2377 Binder.restoreCallingIdentity(origId);
2378 }
2379 }
2380 }
2381
Mark Renouf446251d2019-04-26 10:22:41 -04002382 @Override
2383 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2384 synchronized (mGlobalLock) {
2385 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2386 if (r == null) {
2387 return;
2388 }
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002389 ActivityStack stack = r.getRootTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002390 if (stack != null && stack.isSingleTaskInstance()) {
2391 // Single-task stacks are used for activities which are presented in floating
2392 // windows above full screen activities. Instead of directly finishing the
2393 // task, a task change listener is used to notify SystemUI so the action can be
2394 // handled specially.
Louis Changcdec0802019-11-11 11:45:07 +08002395 final Task task = r.getTask();
Mark Renouf446251d2019-04-26 10:22:41 -04002396 mTaskChangeNotificationController
2397 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2398 } else {
2399 try {
2400 callback.requestFinish();
2401 } catch (RemoteException e) {
2402 Slog.e(TAG, "Failed to invoke request finish callback", e);
2403 }
2404 }
2405 }
2406 }
2407
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002408 /**
2409 * TODO: Add mController hook
2410 */
2411 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002412 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2413 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002414 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002415
2416 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2417 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002418 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2419 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 }
2421 }
2422
Ricky Waiaca8a772019-04-04 16:01:06 +01002423 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2424 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002425 boolean fromRecents) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002426 final int callingPid = Binder.getCallingPid();
2427 final int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002428 assertPackageMatchesCallingUid(callingPackage);
Ricky Waiaca8a772019-04-04 16:01:06 +01002429 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 SafeActivityOptions.abort(options);
2431 return;
2432 }
2433 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002434 WindowProcessController callerApp = null;
2435 if (appThread != null) {
2436 callerApp = getProcessController(appThread);
2437 }
2438 final ActivityStarter starter = getActivityStartController().obtainStarter(
2439 null /* intent */, "moveTaskToFront");
2440 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
Galia Peycheva6861e912019-08-21 10:20:23 +02002441 -1, callerApp, null, false, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002442 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002443 return;
2444 }
2445 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002446 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002447 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002448 if (task == null) {
2449 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002450 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002451 return;
2452 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002453 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002454 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002455 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002456 return;
2457 }
2458 ActivityOptions realOptions = options != null
2459 ? options.getOptions(mStackSupervisor)
2460 : null;
2461 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2462 false /* forceNonResizable */);
2463
Wale Ogunwale21e06482019-11-18 05:14:15 -08002464 final ActivityRecord topActivity = task.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002465 if (topActivity != null) {
2466
2467 // We are reshowing a task, use a starting window to hide the initial draw delay
2468 // so the transition can start earlier.
2469 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2470 true /* taskSwitch */, fromRecents);
2471 }
2472 } finally {
2473 Binder.restoreCallingIdentity(origId);
2474 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475 }
2476
Ricky Waiaca8a772019-04-04 16:01:06 +01002477 /**
2478 * Return true if callingUid is system, or packageName belongs to that callingUid.
2479 */
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002480 private boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002481 try {
2482 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2483 if (packageName == null) {
2484 return false;
2485 }
2486 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2487 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2488 UserHandle.getUserId(callingUid));
2489 return UserHandle.isSameApp(callingUid, uid);
2490 }
2491 } catch (RemoteException e) {
2492 // Should not happen
2493 }
2494 return true;
2495 }
2496
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07002497 /**
2498 * Checks that the provided package name matches the current calling UID, throws a security
2499 * exception if it doesn't.
2500 */
2501 void assertPackageMatchesCallingUid(@Nullable String packageName) {
2502 final int callingUid = Binder.getCallingUid();
2503 if (isSameApp(callingUid, packageName)) {
2504 return;
2505 }
2506 final String msg = "Permission Denial: package=" + packageName
2507 + " does not belong to uid=" + callingUid;
2508 Slog.w(TAG, msg);
2509 throw new SecurityException(msg);
2510 }
2511
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002512 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2513 int callingPid, int callingUid, String name) {
2514 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2515 return true;
2516 }
2517
2518 if (getRecentTasks().isCallerRecents(sourceUid)) {
2519 return true;
2520 }
2521
2522 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2523 if (perm == PackageManager.PERMISSION_GRANTED) {
2524 return true;
2525 }
2526 if (checkAllowAppSwitchUid(sourceUid)) {
2527 return true;
2528 }
2529
2530 // If the actual IPC caller is different from the logical source, then
2531 // also see if they are allowed to control app switches.
2532 if (callingUid != -1 && callingUid != sourceUid) {
2533 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2534 if (perm == PackageManager.PERMISSION_GRANTED) {
2535 return true;
2536 }
2537 if (checkAllowAppSwitchUid(callingUid)) {
2538 return true;
2539 }
2540 }
2541
2542 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2543 return false;
2544 }
2545
2546 private boolean checkAllowAppSwitchUid(int uid) {
2547 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2548 if (types != null) {
2549 for (int i = types.size() - 1; i >= 0; i--) {
2550 if (types.valueAt(i).intValue() == uid) {
2551 return true;
2552 }
2553 }
2554 }
2555 return false;
2556 }
2557
2558 @Override
2559 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2560 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2561 "setActivityController()");
2562 synchronized (mGlobalLock) {
2563 mController = controller;
2564 mControllerIsAMonkey = imAMonkey;
2565 Watchdog.getInstance().setActivityController(controller);
2566 }
2567 }
2568
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002569 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 synchronized (mGlobalLock) {
2571 return mController != null && mControllerIsAMonkey;
2572 }
2573 }
2574
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002575 @Override
2576 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2577 synchronized (mGlobalLock) {
2578 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2579 }
2580 }
2581
2582 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002583 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2584 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2585 }
2586
2587 @Override
2588 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2589 @WindowConfiguration.ActivityType int ignoreActivityType,
2590 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2591 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002592 final int callingPid = Binder.getCallingPid();
2593 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002594 final int[] profileIds = getUserManager().getProfileIds(
2595 UserHandle.getUserId(callingUid), true);
2596 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2597 for (int i = 0; i < profileIds.length; i++) {
2598 callingProfileIds.add(profileIds[i]);
2599 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002600 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2601
2602 synchronized (mGlobalLock) {
2603 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2604
Nicholas Sauer0259e532019-08-30 08:24:55 -07002605 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Louis Chang149d5c82019-12-30 09:47:39 +08002606 mRootWindowContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002607 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 }
2609
2610 return list;
2611 }
2612
2613 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002614 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2615 synchronized (mGlobalLock) {
2616 final long origId = Binder.clearCallingIdentity();
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002617 try {
2618 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2619 if (r == null) return;
2620
2621 final PooledConsumer c = PooledLambda.obtainConsumer(
2622 ActivityRecord::finishIfSubActivity, PooledLambda.__(ActivityRecord.class),
2623 r, resultWho, requestCode);
2624 // TODO: This should probably only loop over the task since you need to be in the
2625 // same task to return results.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002626 r.getRootTask().forAllActivities(c);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002627 c.recycle();
2628
2629 updateOomAdj();
2630 } finally {
2631 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002632 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002633 }
2634 }
2635
2636 @Override
2637 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002638 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639 ActivityStack stack = ActivityRecord.getStackLocked(token);
2640 if (stack != null) {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002641 return stack.willActivityBeVisible(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002642 }
2643 return false;
2644 }
2645 }
2646
2647 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002648 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002649 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002650 synchronized (mGlobalLock) {
2651 final long ident = Binder.clearCallingIdentity();
2652 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002653 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002654 if (task == null) {
2655 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2656 return;
2657 }
2658
2659 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2660 + " to stackId=" + stackId + " toTop=" + toTop);
2661
Louis Chang149d5c82019-12-30 09:47:39 +08002662 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002663 if (stack == null) {
2664 throw new IllegalStateException(
2665 "moveTaskToStack: No stack for stackId=" + stackId);
2666 }
2667 if (!stack.isActivityTypeStandardOrUndefined()) {
2668 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2669 + taskId + " to stack " + stackId);
2670 }
2671 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002672 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002673 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2674 }
2675 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2676 "moveTaskToStack");
2677 } finally {
2678 Binder.restoreCallingIdentity(ident);
2679 }
2680 }
2681 }
2682
2683 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002684 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2685 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002686
2687 final long ident = Binder.clearCallingIdentity();
2688 try {
2689 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002690 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Evan Roskydbe2ce52019-07-18 11:13:17 -07002691 if (stack == null) {
2692 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2693 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002694 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002695 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2696 throw new IllegalArgumentException("Stack: " + stackId
2697 + " doesn't support animated resize.");
2698 }
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002699 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
Evan Roskydbe2ce52019-07-18 11:13:17 -07002700 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 }
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706
wilsonshih5c4cf522019-01-25 09:03:47 +08002707 @Override
2708 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2709 int animationDuration) {
2710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2711
2712 final long ident = Binder.clearCallingIdentity();
2713 try {
2714 synchronized (mGlobalLock) {
2715 if (xOffset == 0 && yOffset == 0) {
2716 return;
2717 }
Louis Chang149d5c82019-12-30 09:47:39 +08002718 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
wilsonshih5c4cf522019-01-25 09:03:47 +08002719 if (stack == null) {
2720 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2721 return;
2722 }
2723 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2724 throw new IllegalArgumentException("Stack: " + stackId
2725 + " doesn't support animated resize.");
2726 }
2727 final Rect destBounds = new Rect();
2728 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002729 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002730 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2731 return;
2732 }
2733 destBounds.offset(xOffset, yOffset);
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07002734 stack.animateResizePinnedStack(destBounds, null /* sourceHintBounds */,
wilsonshih5c4cf522019-01-25 09:03:47 +08002735 animationDuration, false /* fromFullscreen */);
2736 }
2737 } finally {
2738 Binder.restoreCallingIdentity(ident);
2739 }
2740 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002741 /**
2742 * Moves the specified task to the primary-split-screen stack.
2743 *
2744 * @param taskId Id of task to move.
2745 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2746 * exist already. See
2747 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2748 * and
2749 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2750 * @param toTop If the task and stack should be moved to the top.
2751 * @param animate Whether we should play an animation for the moving the task.
2752 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2753 * stack. Pass {@code null} to use default bounds.
2754 * @param showRecents If the recents activity should be shown on the other side of the task
2755 * going into split-screen mode.
Winson Chung7ccc6812020-01-23 16:15:10 -08002756 * @return Whether the task was successfully put into splitscreen.
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002757 */
2758 @Override
2759 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2760 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002761 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002762 "setTaskWindowingModeSplitScreenPrimary()");
2763 synchronized (mGlobalLock) {
2764 final long ident = Binder.clearCallingIdentity();
2765 try {
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002766 return setTaskWindowingModeSplitScreen(taskId, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY,
2767 toTop);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772 }
2773
2774 /**
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002775 * Moves the specified task into a split-screen tile.
2776 */
2777 private boolean setTaskWindowingModeSplitScreen(int taskId, int windowingMode, boolean toTop) {
2778 if (!WindowConfiguration.isSplitScreenWindowingMode(windowingMode)) {
2779 throw new IllegalArgumentException("Calling setTaskWindowingModeSplitScreen with non"
2780 + "split-screen mode: " + windowingMode);
2781 }
2782 if (isInLockTaskMode()) {
2783 Slog.w(TAG, "setTaskWindowingModeSplitScreen: Is in lock task mode="
2784 + getLockTaskModeState());
2785 return false;
2786 }
2787
2788 final Task task = mRootWindowContainer.anyTaskForId(taskId,
2789 MATCH_TASK_IN_STACKS_ONLY);
2790 if (task == null) {
2791 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2792 return false;
2793 }
2794 if (!task.isActivityTypeStandardOrUndefined()) {
2795 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2796 + " non-standard task " + taskId + " to split-screen windowing mode");
2797 }
Wale Ogunwale0d465192020-01-23 19:14:44 -08002798 if (!task.supportsSplitScreenWindowingMode()) {
2799 return false;
2800 }
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002801
2802 final int prevMode = task.getWindowingMode();
Wale Ogunwale0d465192020-01-23 19:14:44 -08002803 moveTaskToSplitScreenPrimaryTile(task, toTop);
2804 return prevMode != task.getWindowingMode();
2805 }
2806
2807 void moveTaskToSplitScreenPrimaryTile(Task task, boolean toTop) {
2808 ActivityStack stack = task.getStack();
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002809 TaskTile tile = null;
2810 for (int i = stack.getDisplay().getStackCount() - 1; i >= 0; --i) {
2811 tile = stack.getDisplay().getStackAt(i).asTile();
2812 if (tile != null && tile.getWindowingMode() == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2813 break;
2814 }
2815 }
2816 if (tile == null) {
2817 throw new IllegalStateException("Can't enter split without associated tile");
2818 }
2819 WindowContainerTransaction wct = new WindowContainerTransaction();
2820 wct.reparent(stack.mRemoteToken, tile.mRemoteToken, toTop);
2821 mTaskOrganizerController.applyContainerTransaction(wct, null);
Evan Roskyaf9f27c2020-02-18 18:58:35 +00002822 }
2823
2824 /**
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002825 * Removes stacks in the input windowing modes from the system if they are of activity type
2826 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2827 */
2828 @Override
2829 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002830 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002831 "removeStacksInWindowingModes()");
2832
2833 synchronized (mGlobalLock) {
2834 final long ident = Binder.clearCallingIdentity();
2835 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002836 mRootWindowContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002837 } finally {
2838 Binder.restoreCallingIdentity(ident);
2839 }
2840 }
2841 }
2842
2843 @Override
2844 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002845 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002846 "removeStacksWithActivityTypes()");
2847
2848 synchronized (mGlobalLock) {
2849 final long ident = Binder.clearCallingIdentity();
2850 try {
Louis Chang149d5c82019-12-30 09:47:39 +08002851 mRootWindowContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002852 } finally {
2853 Binder.restoreCallingIdentity(ident);
2854 }
2855 }
2856 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002857
2858 @Override
2859 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2860 int userId) {
2861 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002862 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2863 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002865 final boolean detailed = checkGetTasksPermission(
2866 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2867 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002868 == PackageManager.PERMISSION_GRANTED;
2869
2870 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002871 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002872 callingUid);
2873 }
2874 }
2875
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002876 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 @Override
2878 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002879 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 long ident = Binder.clearCallingIdentity();
2881 try {
2882 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002883 return mRootWindowContainer.getAllStackInfos(INVALID_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 }
2885 } finally {
2886 Binder.restoreCallingIdentity(ident);
2887 }
2888 }
2889
2890 @Override
2891 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002892 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002893 long ident = Binder.clearCallingIdentity();
2894 try {
2895 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002896 return mRootWindowContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 }
2898 } finally {
2899 Binder.restoreCallingIdentity(ident);
2900 }
2901 }
2902
Evan Rosky29d4a0a2020-02-04 16:40:44 -08002903 // TODO(148895075): deprecate and replace with task equivalents
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002904 @Override
Evan Roskyfd439692019-11-06 16:12:59 -08002905 public List<ActivityManager.StackInfo> getAllStackInfosOnDisplay(int displayId) {
2906 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
2907 long ident = Binder.clearCallingIdentity();
2908 try {
2909 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002910 return mRootWindowContainer.getAllStackInfos(displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002911 }
2912 } finally {
2913 Binder.restoreCallingIdentity(ident);
2914 }
2915 }
2916
2917 @Override
2918 public ActivityManager.StackInfo getStackInfoOnDisplay(int windowingMode, int activityType,
2919 int displayId) {
2920 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
2921 long ident = Binder.clearCallingIdentity();
2922 try {
2923 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002924 return mRootWindowContainer.getStackInfo(windowingMode, activityType, displayId);
Evan Roskyfd439692019-11-06 16:12:59 -08002925 }
2926 } finally {
2927 Binder.restoreCallingIdentity(ident);
2928 }
2929 }
2930
2931 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002932 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002933 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002934 final long callingUid = Binder.getCallingUid();
2935 final long origId = Binder.clearCallingIdentity();
2936 try {
2937 synchronized (mGlobalLock) {
2938 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002939 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002940 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2941 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2942 }
2943 } finally {
2944 Binder.restoreCallingIdentity(origId);
2945 }
2946 }
2947
2948 @Override
2949 public void startLockTaskModeByToken(IBinder token) {
2950 synchronized (mGlobalLock) {
2951 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2952 if (r == null) {
2953 return;
2954 }
Louis Changcdec0802019-11-11 11:45:07 +08002955 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 }
2957 }
2958
2959 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002960 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002961 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002962 // This makes inner call to look as if it was initiated by system.
2963 long ident = Binder.clearCallingIdentity();
2964 try {
2965 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08002966 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002967 MATCH_TASK_IN_STACKS_ONLY);
2968 if (task == null) {
2969 return;
2970 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971
2972 // When starting lock task mode the stack must be in front and focused
2973 task.getStack().moveToFront("startSystemLockTaskMode");
2974 startLockTaskModeLocked(task, true /* isSystemCaller */);
2975 }
2976 } finally {
2977 Binder.restoreCallingIdentity(ident);
2978 }
2979 }
2980
2981 @Override
2982 public void stopLockTaskModeByToken(IBinder token) {
2983 synchronized (mGlobalLock) {
2984 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2985 if (r == null) {
2986 return;
2987 }
Louis Changcdec0802019-11-11 11:45:07 +08002988 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002989 }
2990 }
2991
2992 /**
2993 * This API should be called by SystemUI only when user perform certain action to dismiss
2994 * lock task mode. We should only dismiss pinned lock task mode in this case.
2995 */
2996 @Override
2997 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002998 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 stopLockTaskModeInternal(null, true /* isSystemCaller */);
3000 }
3001
Louis Changcdec0802019-11-11 11:45:07 +08003002 private void startLockTaskModeLocked(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003003 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
3004 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
3005 return;
3006 }
3007
Louis Chang149d5c82019-12-30 09:47:39 +08003008 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09003009 if (stack == null || task != stack.getTopMostTask()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 throw new IllegalArgumentException("Invalid task, not in foreground");
3011 }
3012
3013 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
3014 // system or a specific app.
3015 // * System-initiated requests will only start the pinned mode (screen pinning)
3016 // * App-initiated requests
3017 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
3018 // - will start the pinned mode, otherwise
3019 final int callingUid = Binder.getCallingUid();
3020 long ident = Binder.clearCallingIdentity();
3021 try {
3022 // When a task is locked, dismiss the pinned stack if it exists
Louis Chang149d5c82019-12-30 09:47:39 +08003023 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003025 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003026 } finally {
3027 Binder.restoreCallingIdentity(ident);
3028 }
3029 }
3030
Louis Changcdec0802019-11-11 11:45:07 +08003031 private void stopLockTaskModeInternal(@Nullable Task task, boolean isSystemCaller) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 final int callingUid = Binder.getCallingUid();
3033 long ident = Binder.clearCallingIdentity();
3034 try {
3035 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003036 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037 }
3038 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
3039 // task and jumping straight into a call in the case of emergency call back.
3040 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3041 if (tm != null) {
3042 tm.showInCallScreen(false);
3043 }
3044 } finally {
3045 Binder.restoreCallingIdentity(ident);
3046 }
3047 }
3048
3049 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003050 public void updateLockTaskPackages(int userId, String[] packages) {
3051 final int callingUid = Binder.getCallingUid();
3052 if (callingUid != 0 && callingUid != SYSTEM_UID) {
3053 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
3054 "updateLockTaskPackages()");
3055 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08003056 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07003057 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
3058 + Arrays.toString(packages));
3059 getLockTaskController().updateLockTaskPackages(userId, packages);
3060 }
3061 }
3062
3063 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003064 public boolean isInLockTaskMode() {
3065 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
3066 }
3067
3068 @Override
3069 public int getLockTaskModeState() {
3070 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003071 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 }
3073 }
3074
3075 @Override
3076 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
3077 synchronized (mGlobalLock) {
3078 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3079 if (r != null) {
3080 r.setTaskDescription(td);
Louis Changcdec0802019-11-11 11:45:07 +08003081 final Task task = r.getTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003082 task.updateTaskDescription();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 }
3084 }
3085 }
3086
3087 @Override
3088 public Bundle getActivityOptions(IBinder token) {
3089 final long origId = Binder.clearCallingIdentity();
3090 try {
3091 synchronized (mGlobalLock) {
3092 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3093 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02003094 final ActivityOptions activityOptions = r.takeOptionsLocked(
3095 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003096 return activityOptions == null ? null : activityOptions.toBundle();
3097 }
3098 return null;
3099 }
3100 } finally {
3101 Binder.restoreCallingIdentity(origId);
3102 }
3103 }
3104
3105 @Override
3106 public List<IBinder> getAppTasks(String callingPackage) {
3107 int callingUid = Binder.getCallingUid();
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07003108 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003109 long ident = Binder.clearCallingIdentity();
3110 try {
3111 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003112 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 }
3114 } finally {
3115 Binder.restoreCallingIdentity(ident);
3116 }
3117 }
3118
3119 @Override
3120 public void finishVoiceTask(IVoiceInteractionSession session) {
3121 synchronized (mGlobalLock) {
3122 final long origId = Binder.clearCallingIdentity();
3123 try {
3124 // TODO: VI Consider treating local voice interactions and voice tasks
3125 // differently here
Louis Chang149d5c82019-12-30 09:47:39 +08003126 mRootWindowContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 } finally {
3128 Binder.restoreCallingIdentity(origId);
3129 }
3130 }
3131
3132 }
3133
3134 @Override
3135 public boolean isTopOfTask(IBinder token) {
3136 synchronized (mGlobalLock) {
3137 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003138 return r != null && r.getTask().getTopNonFinishingActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 }
3140 }
3141
3142 @Override
3143 public void notifyLaunchTaskBehindComplete(IBinder token) {
3144 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3145 }
3146
3147 @Override
3148 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003149 mH.post(() -> {
3150 synchronized (mGlobalLock) {
3151 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003152 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003153 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003154 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003155 } catch (RemoteException e) {
3156 }
3157 }
3158 }
3159
3160 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 }
3162
3163 /** Called from an app when assist data is ready. */
3164 @Override
3165 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3166 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003167 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 synchronized (pae) {
3169 pae.result = extras;
3170 pae.structure = structure;
3171 pae.content = content;
3172 if (referrer != null) {
3173 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3174 }
3175 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003176 // Pre-fill the task/activity component for all assist data receivers
Louis Changcdec0802019-11-11 11:45:07 +08003177 structure.setTaskId(pae.activity.getTask().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003178 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 structure.setHomeActivity(pae.isHome);
3180 }
3181 pae.haveResult = true;
3182 pae.notifyAll();
3183 if (pae.intent == null && pae.receiver == null) {
3184 // Caller is just waiting for the result.
3185 return;
3186 }
3187 }
3188 // We are now ready to launch the assist activity.
3189 IAssistDataReceiver sendReceiver = null;
3190 Bundle sendBundle = null;
3191 synchronized (mGlobalLock) {
3192 buildAssistBundleLocked(pae, extras);
3193 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003194 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 if (!exists) {
3196 // Timed out.
3197 return;
3198 }
3199
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 // Caller wants result sent back to them.
3202 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003203 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Louis Changcdec0802019-11-11 11:45:07 +08003204 pae.activity.getTask().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003205 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3206 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3208 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3209 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3210 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3211 }
3212 }
3213 if (sendReceiver != null) {
3214 try {
3215 sendReceiver.onHandleAssistData(sendBundle);
3216 } catch (RemoteException e) {
3217 }
3218 return;
3219 }
3220
3221 final long ident = Binder.clearCallingIdentity();
3222 try {
3223 if (TextUtils.equals(pae.intent.getAction(),
3224 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003225 // Start voice interaction through VoiceInteractionManagerService.
3226 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3227 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003228 } else {
3229 pae.intent.replaceExtras(pae.extras);
3230 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3231 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3232 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003233 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003234
3235 try {
3236 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3237 } catch (ActivityNotFoundException e) {
3238 Slog.w(TAG, "No activity to handle assist action.", e);
3239 }
3240 }
3241 } finally {
3242 Binder.restoreCallingIdentity(ident);
3243 }
3244 }
3245
3246 @Override
3247 public int addAppTask(IBinder activityToken, Intent intent,
3248 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3249 final int callingUid = Binder.getCallingUid();
3250 final long callingIdent = Binder.clearCallingIdentity();
3251
3252 try {
3253 synchronized (mGlobalLock) {
3254 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3255 if (r == null) {
3256 throw new IllegalArgumentException("Activity does not exist; token="
3257 + activityToken);
3258 }
3259 ComponentName comp = intent.getComponent();
3260 if (comp == null) {
3261 throw new IllegalArgumentException("Intent " + intent
3262 + " must specify explicit component");
3263 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003264 if (thumbnail.getWidth() != mThumbnailWidth
3265 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 throw new IllegalArgumentException("Bad thumbnail size: got "
3267 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003268 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 }
3270 if (intent.getSelector() != null) {
3271 intent.setSelector(null);
3272 }
3273 if (intent.getSourceBounds() != null) {
3274 intent.setSourceBounds(null);
3275 }
3276 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3277 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3278 // The caller has added this as an auto-remove task... that makes no
3279 // sense, so turn off auto-remove.
3280 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3281 }
3282 }
3283 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3284 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3285 if (ainfo.applicationInfo.uid != callingUid) {
3286 throw new SecurityException(
3287 "Can't add task for another application: target uid="
3288 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3289 }
3290
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003291 final ActivityStack stack = r.getRootTask();
Wale Ogunwale0d465192020-01-23 19:14:44 -08003292 final Task task = stack.getDisplay().createStack(stack.getWindowingMode(),
3293 stack.getActivityType(), !ON_TOP, ainfo, intent);
3294
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003295 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003296 // The app has too many tasks already and we can't add any more
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003297 stack.removeChild(task, "addAppTask");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003298 return INVALID_TASK_ID;
3299 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02003300 task.getTaskDescription().copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301
3302 // TODO: Send the thumbnail to WM to store it.
3303
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003304 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305 }
3306 } finally {
3307 Binder.restoreCallingIdentity(callingIdent);
3308 }
3309 }
3310
3311 @Override
3312 public Point getAppTaskThumbnailSize() {
3313 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 }
3316 }
3317
3318 @Override
3319 public void setTaskResizeable(int taskId, int resizeableMode) {
3320 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003321 final Task task = mRootWindowContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3323 if (task == null) {
3324 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3325 return;
3326 }
3327 task.setResizeMode(resizeableMode);
3328 }
3329 }
3330
3331 @Override
3332 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003333 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003334 long ident = Binder.clearCallingIdentity();
3335 try {
3336 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08003337 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003338 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003339 if (task == null) {
3340 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3341 return;
3342 }
3343 // Place the task in the right stack if it isn't there already based on
3344 // the requested bounds.
3345 // The stack transition logic is:
3346 // - a null bounds on a freeform task moves that task to fullscreen
3347 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3348 // that task to freeform
3349 // - otherwise the task is not moved
3350 ActivityStack stack = task.getStack();
3351 if (!task.getWindowConfiguration().canResizeTask()) {
3352 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3353 }
3354 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3355 stack = stack.getDisplay().getOrCreateStack(
3356 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3357 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3358 stack = stack.getDisplay().getOrCreateStack(
3359 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3360 }
3361
3362 // Reparent the task to the right stack if necessary
3363 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3364 if (stack != task.getStack()) {
3365 // Defer resume until the task is resized below
3366 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3367 DEFER_RESUME, "resizeTask");
3368 preserveWindow = false;
3369 }
3370
3371 // After reparenting (which only resizes the task to the stack bounds), resize the
3372 // task to the actual bounds provided
3373 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3374 }
3375 } finally {
3376 Binder.restoreCallingIdentity(ident);
3377 }
3378 }
3379
3380 @Override
3381 public boolean releaseActivityInstance(IBinder token) {
3382 synchronized (mGlobalLock) {
3383 final long origId = Binder.clearCallingIdentity();
3384 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003385 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3386 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003387 return false;
3388 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003389 r.destroyImmediately(true /* removeFromApp */, "app-req");
3390 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 } finally {
3392 Binder.restoreCallingIdentity(origId);
3393 }
3394 }
3395 }
3396
3397 @Override
3398 public void releaseSomeActivities(IApplicationThread appInt) {
3399 synchronized (mGlobalLock) {
3400 final long origId = Binder.clearCallingIdentity();
3401 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003402 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwalea38654f2019-11-17 20:37:15 -08003403 app.releaseSomeActivities("low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 } finally {
3405 Binder.restoreCallingIdentity(origId);
3406 }
3407 }
3408 }
3409
3410 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003411 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003412 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413 != PackageManager.PERMISSION_GRANTED) {
3414 throw new SecurityException("Requires permission "
3415 + android.Manifest.permission.DEVICE_POWER);
3416 }
3417
3418 synchronized (mGlobalLock) {
3419 long ident = Binder.clearCallingIdentity();
3420 if (mKeyguardShown != keyguardShowing) {
3421 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003422 final Message msg = PooledLambda.obtainMessage(
3423 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3424 keyguardShowing);
3425 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 }
3427 try {
wilsonshih177261f2019-02-22 12:02:18 +08003428 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 mH.post(() -> {
3435 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3436 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3437 }
3438 });
3439 }
3440
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003441 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003442 mH.post(() -> {
3443 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3444 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3445 }
3446 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 }
3448
3449 @Override
3450 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003451 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3452 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003453
3454 final File passedIconFile = new File(filePath);
3455 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3456 passedIconFile.getName());
3457 if (!legitIconFile.getPath().equals(filePath)
3458 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3459 throw new IllegalArgumentException("Bad file path: " + filePath
3460 + " passed for userId " + userId);
3461 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003462 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003463 }
3464
3465 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 synchronized (mGlobalLock) {
3469 final long ident = Binder.clearCallingIdentity();
3470 try {
Louis Chang149d5c82019-12-30 09:47:39 +08003471 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 if (stack == null) {
3473 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3474 return;
3475 }
3476 if (!stack.isActivityTypeStandardOrUndefined()) {
3477 throw new IllegalArgumentException(
3478 "Removing non-standard stack is not allowed.");
3479 }
3480 mStackSupervisor.removeStack(stack);
3481 } finally {
3482 Binder.restoreCallingIdentity(ident);
3483 }
3484 }
3485 }
3486
3487 @Override
3488 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003489 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003490
3491 synchronized (mGlobalLock) {
3492 final long ident = Binder.clearCallingIdentity();
3493 try {
3494 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3495 + " to displayId=" + displayId);
Louis Chang149d5c82019-12-30 09:47:39 +08003496 mRootWindowContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
3500 }
3501 }
3502
3503 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003504 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003505 synchronized (mGlobalLock) {
3506 long ident = Binder.clearCallingIdentity();
3507 try {
3508 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3509 if (r == null) {
3510 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003511 "toggleFreeformWindowingMode: No activity record matching token="
3512 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003513 }
3514
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08003515 final ActivityStack stack = r.getRootTask();
Yunfan Chend967af82019-01-17 18:30:18 +09003516 if (stack == null) {
3517 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3518 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003519 }
3520
Yunfan Chend967af82019-01-17 18:30:18 +09003521 if (!stack.inFreeformWindowingMode()
3522 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3523 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3524 + "toggle between fullscreen and freeform.");
3525 }
3526
3527 if (stack.inFreeformWindowingMode()) {
3528 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Evan Rosky3a8d7fe2019-11-06 17:08:35 -08003529 } else if (!mSizeCompatFreeform && r.inSizeCompatMode()) {
Shivam Agrawal780b5bb2019-07-17 10:17:11 -07003530 throw new IllegalStateException("Size-compat windows are currently not"
3531 + "freeform-enabled");
Yunfan Chene9c1c312019-04-18 14:49:15 +09003532 } else if (stack.getParent().inFreeformWindowingMode()) {
3533 // If the window is on a freeform display, set it to undefined. It will be
3534 // resolved to freeform and it can adjust windowing mode when the display mode
3535 // changes in runtime.
3536 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003537 } else {
3538 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3539 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003540 } finally {
3541 Binder.restoreCallingIdentity(ident);
3542 }
3543 }
3544 }
3545
3546 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3547 @Override
3548 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003549 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003551 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003552 }
3553
3554 /** Unregister a task stack listener so that it stops receiving callbacks. */
3555 @Override
3556 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003559 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 }
3561
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 @Override
3563 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3564 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3565 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3566 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3567 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3568 }
3569
3570 @Override
3571 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3572 IBinder activityToken, int flags) {
3573 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3574 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3575 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3576 }
3577
3578 @Override
3579 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3580 Bundle args) {
3581 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3582 true /* focused */, true /* newSessionId */, userHandle, args,
3583 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3584 }
3585
3586 @Override
3587 public Bundle getAssistContextExtras(int requestType) {
3588 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3589 null, null, true /* focused */, true /* newSessionId */,
3590 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3591 if (pae == null) {
3592 return null;
3593 }
3594 synchronized (pae) {
3595 while (!pae.haveResult) {
3596 try {
3597 pae.wait();
3598 } catch (InterruptedException e) {
3599 }
3600 }
3601 }
3602 synchronized (mGlobalLock) {
3603 buildAssistBundleLocked(pae, pae.result);
3604 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003605 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 }
3607 return pae.extras;
3608 }
3609
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003610 /**
3611 * Binder IPC calls go through the public entry point.
3612 * This can be called with or without the global lock held.
3613 */
3614 private static int checkCallingPermission(String permission) {
3615 return checkPermission(
3616 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3617 }
3618
3619 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003620 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003621 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3622 mAmInternal.enforceCallingPermission(permission, func);
3623 }
3624 }
3625
3626 @VisibleForTesting
3627 int checkGetTasksPermission(String permission, int pid, int uid) {
3628 return checkPermission(permission, pid, uid);
3629 }
3630
3631 static int checkPermission(String permission, int pid, int uid) {
3632 if (permission == null) {
3633 return PackageManager.PERMISSION_DENIED;
3634 }
3635 return checkComponentPermission(permission, pid, uid, -1, true);
3636 }
3637
Wale Ogunwale214f3482018-10-04 11:00:47 -07003638 public static int checkComponentPermission(String permission, int pid, int uid,
3639 int owningUid, boolean exported) {
3640 return ActivityManagerService.checkComponentPermission(
3641 permission, pid, uid, owningUid, exported);
3642 }
3643
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003644 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3645 if (getRecentTasks().isCallerRecents(callingUid)) {
3646 // Always allow the recents component to get tasks
3647 return true;
3648 }
3649
3650 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3651 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3652 if (!allowed) {
3653 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3654 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3655 // Temporary compatibility: some existing apps on the system image may
3656 // still be requesting the old permission and not switched to the new
3657 // one; if so, we'll still allow them full access. This means we need
3658 // to see if they are holding the old permission and are a system app.
3659 try {
3660 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3661 allowed = true;
3662 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3663 + " is using old GET_TASKS but privileged; allowing");
3664 }
3665 } catch (RemoteException e) {
3666 }
3667 }
3668 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3669 + " does not hold REAL_GET_TASKS; limiting output");
3670 }
3671 return allowed;
3672 }
3673
Nicholas Sauer0259e532019-08-30 08:24:55 -07003674 boolean isCrossUserAllowed(int pid, int uid) {
3675 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3676 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3677 }
3678
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003679 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3680 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3681 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3682 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003683 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003684 "enqueueAssistContext()");
3685
3686 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08003687 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003688 if (activity == null) {
3689 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3690 return null;
3691 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003692 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3694 return null;
3695 }
3696 if (focused) {
3697 if (activityToken != null) {
3698 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3699 if (activity != caller) {
3700 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3701 + " is not current top " + activity);
3702 return null;
3703 }
3704 }
3705 } else {
3706 activity = ActivityRecord.forTokenLocked(activityToken);
3707 if (activity == null) {
3708 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3709 + " couldn't be found");
3710 return null;
3711 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003712 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003713 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3714 return null;
3715 }
3716 }
3717
3718 PendingAssistExtras pae;
3719 Bundle extras = new Bundle();
3720 if (args != null) {
3721 extras.putAll(args);
3722 }
3723 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003724 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003725
3726 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3727 userHandle);
3728 pae.isHome = activity.isActivityTypeHome();
3729
3730 // Increment the sessionId if necessary
3731 if (newSessionId) {
3732 mViSessionId++;
3733 }
3734 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003735 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3736 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003738 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 } catch (RemoteException e) {
3740 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3741 return null;
3742 }
3743 return pae;
3744 }
3745 }
3746
3747 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3748 if (result != null) {
3749 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3750 }
3751 if (pae.hint != null) {
3752 pae.extras.putBoolean(pae.hint, true);
3753 }
3754 }
3755
3756 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3757 IAssistDataReceiver receiver;
3758 synchronized (mGlobalLock) {
3759 mPendingAssistExtras.remove(pae);
3760 receiver = pae.receiver;
3761 }
3762 if (receiver != null) {
3763 // Caller wants result sent back to them.
3764 Bundle sendBundle = new Bundle();
3765 // At least return the receiver extras
3766 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3767 try {
3768 pae.receiver.onHandleAssistData(sendBundle);
3769 } catch (RemoteException e) {
3770 }
3771 }
3772 }
3773
3774 public class PendingAssistExtras extends Binder implements Runnable {
3775 public final ActivityRecord activity;
3776 public boolean isHome;
3777 public final Bundle extras;
3778 public final Intent intent;
3779 public final String hint;
3780 public final IAssistDataReceiver receiver;
3781 public final int userHandle;
3782 public boolean haveResult = false;
3783 public Bundle result = null;
3784 public AssistStructure structure = null;
3785 public AssistContent content = null;
3786 public Bundle receiverExtras;
3787
3788 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3789 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3790 int _userHandle) {
3791 activity = _activity;
3792 extras = _extras;
3793 intent = _intent;
3794 hint = _hint;
3795 receiver = _receiver;
3796 receiverExtras = _receiverExtras;
3797 userHandle = _userHandle;
3798 }
3799
3800 @Override
3801 public void run() {
3802 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3803 synchronized (this) {
3804 haveResult = true;
3805 notifyAll();
3806 }
3807 pendingAssistExtrasTimedOut(this);
3808 }
3809 }
3810
3811 @Override
3812 public boolean isAssistDataAllowedOnCurrentActivity() {
3813 int userId;
3814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003815 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3817 return false;
3818 }
3819
Wale Ogunwale21e06482019-11-18 05:14:15 -08003820 final ActivityRecord activity = focusedStack.getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 if (activity == null) {
3822 return false;
3823 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003824 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003825 }
3826 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3827 }
3828
3829 @Override
3830 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3831 long ident = Binder.clearCallingIdentity();
3832 try {
3833 synchronized (mGlobalLock) {
3834 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Wale Ogunwale21e06482019-11-18 05:14:15 -08003835 ActivityRecord top = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 if (top != caller) {
3837 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3838 + " is not current top " + top);
3839 return false;
3840 }
3841 if (!top.nowVisible) {
3842 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3843 + " is not visible");
3844 return false;
3845 }
3846 }
3847 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3848 token);
3849 } finally {
3850 Binder.restoreCallingIdentity(ident);
3851 }
3852 }
3853
3854 @Override
3855 public boolean isRootVoiceInteraction(IBinder token) {
3856 synchronized (mGlobalLock) {
3857 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3858 if (r == null) {
3859 return false;
3860 }
3861 return r.rootVoiceInteraction;
3862 }
3863 }
3864
Wale Ogunwalef6733932018-06-27 05:14:34 -07003865 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3866 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3867 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3868 if (activityToCallback == null) return;
3869 activityToCallback.setVoiceSessionLocked(voiceSession);
3870
3871 // Inform the activity
3872 try {
3873 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3874 voiceInteractor);
3875 long token = Binder.clearCallingIdentity();
3876 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003877 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003878 } finally {
3879 Binder.restoreCallingIdentity(token);
3880 }
3881 // TODO: VI Should we cache the activity so that it's easier to find later
3882 // rather than scan through all the stacks and activities?
3883 } catch (RemoteException re) {
3884 activityToCallback.clearVoiceSessionLocked();
3885 // TODO: VI Should this terminate the voice session?
3886 }
3887 }
3888
3889 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3890 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3891 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3892 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3893 boolean wasRunningVoice = mRunningVoice != null;
3894 mRunningVoice = session;
3895 if (!wasRunningVoice) {
3896 mVoiceWakeLock.acquire();
3897 updateSleepIfNeededLocked();
3898 }
3899 }
3900 }
3901
3902 void finishRunningVoiceLocked() {
3903 if (mRunningVoice != null) {
3904 mRunningVoice = null;
3905 mVoiceWakeLock.release();
3906 updateSleepIfNeededLocked();
3907 }
3908 }
3909
3910 @Override
3911 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3912 synchronized (mGlobalLock) {
3913 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3914 if (keepAwake) {
3915 mVoiceWakeLock.acquire();
3916 } else {
3917 mVoiceWakeLock.release();
3918 }
3919 }
3920 }
3921 }
3922
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 @Override
3924 public ComponentName getActivityClassForToken(IBinder token) {
3925 synchronized (mGlobalLock) {
3926 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3927 if (r == null) {
3928 return null;
3929 }
3930 return r.intent.getComponent();
3931 }
3932 }
3933
3934 @Override
3935 public String getPackageForToken(IBinder token) {
3936 synchronized (mGlobalLock) {
3937 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3938 if (r == null) {
3939 return null;
3940 }
3941 return r.packageName;
3942 }
3943 }
3944
3945 @Override
3946 public void showLockTaskEscapeMessage(IBinder token) {
3947 synchronized (mGlobalLock) {
3948 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3949 if (r == null) {
3950 return;
3951 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003952 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 }
3954 }
3955
3956 @Override
3957 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003958 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003959 final long token = Binder.clearCallingIdentity();
3960 try {
3961 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003962 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 }
3964 } finally {
3965 Binder.restoreCallingIdentity(token);
3966 }
3967 }
3968
3969 /**
3970 * Try to place task to provided position. The final position might be different depending on
3971 * current user and stacks state. The task will be moved to target stack if it's currently in
3972 * different stack.
3973 */
3974 @Override
3975 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003976 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 synchronized (mGlobalLock) {
3978 long ident = Binder.clearCallingIdentity();
3979 try {
3980 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3981 + taskId + " in stackId=" + stackId + " at position=" + position);
Louis Chang149d5c82019-12-30 09:47:39 +08003982 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003983 if (task == null) {
3984 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3985 + taskId);
3986 }
3987
Louis Chang149d5c82019-12-30 09:47:39 +08003988 final ActivityStack stack = mRootWindowContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989
3990 if (stack == null) {
3991 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3992 + stackId);
3993 }
3994 if (!stack.isActivityTypeStandardOrUndefined()) {
3995 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3996 + " the position of task " + taskId + " in/to non-standard stack");
3997 }
3998
3999 // TODO: Have the callers of this API call a separate reparent method if that is
4000 // what they intended to do vs. having this method also do reparenting.
4001 if (task.getStack() == stack) {
4002 // Change position in current stack.
4003 stack.positionChildAt(task, position);
4004 } else {
4005 // Reparent to new stack.
4006 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
4007 !DEFER_RESUME, "positionTaskInStack");
4008 }
4009 } finally {
4010 Binder.restoreCallingIdentity(ident);
4011 }
4012 }
4013 }
4014
4015 @Override
4016 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
4017 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
4018 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09004019 + Arrays.toString(horizontalSizeConfiguration) + " "
4020 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004021 synchronized (mGlobalLock) {
4022 ActivityRecord record = ActivityRecord.isInStackLocked(token);
4023 if (record == null) {
4024 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
4025 + "found for: " + token);
4026 }
4027 record.setSizeConfigurations(horizontalSizeConfiguration,
4028 verticalSizeConfigurations, smallestSizeConfigurations);
4029 }
4030 }
4031
4032 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 * Dismisses Pip
4034 * @param animate True if the dismissal should be animated.
4035 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
4036 * default animation duration should be used.
4037 */
4038 @Override
4039 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004040 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 final long ident = Binder.clearCallingIdentity();
4042 try {
4043 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004044 final ActivityStack stack =
Wale Ogunwale734b8962020-01-21 12:17:42 -08004045 mRootWindowContainer.getDefaultDisplay().getRootPinnedTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 if (stack == null) {
4047 Slog.w(TAG, "dismissPip: pinned stack not found.");
4048 return;
4049 }
4050 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4051 throw new IllegalArgumentException("Stack: " + stack
4052 + " doesn't support animated resize.");
4053 }
Robert Carr8a2f9132019-11-11 15:03:15 -08004054 /**
4055 * TODO(b/146594635): Remove all PIP animation code from WM
4056 * once SysUI handles animation. Don't even try to animate TaskOrganized tasks.
4057 */
4058 if (animate && !stack.isControlledByTaskOrganizer()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07004059 stack.animateResizePinnedStack(null /* destBounds */,
4060 null /* sourceHintBounds */, animationDuration,
4061 false /* fromFullscreen */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 } else {
Ben Lin6db8fb22019-10-18 16:03:44 -07004063 stack.dismissPip();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064 }
4065 }
4066 } finally {
4067 Binder.restoreCallingIdentity(ident);
4068 }
4069 }
4070
4071 @Override
4072 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004073 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 synchronized (mGlobalLock) {
4075 mSuppressResizeConfigChanges = suppress;
4076 }
4077 }
4078
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004079 @Override
4080 // TODO: API should just be about changing windowing modes...
4081 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004082 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 "moveTasksToFullscreenStack()");
4084 synchronized (mGlobalLock) {
4085 final long origId = Binder.clearCallingIdentity();
4086 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004087 final ActivityStack stack = mRootWindowContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 if (stack != null){
4089 if (!stack.isActivityTypeStandardOrUndefined()) {
4090 throw new IllegalArgumentException(
4091 "You can't move tasks from non-standard stacks.");
4092 }
4093 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4094 }
4095 } finally {
4096 Binder.restoreCallingIdentity(origId);
4097 }
4098 }
4099 }
4100
4101 /**
4102 * Moves the top activity in the input stackId to the pinned stack.
4103 *
4104 * @param stackId Id of stack to move the top activity to pinned stack.
4105 * @param bounds Bounds to use for pinned stack.
4106 *
4107 * @return True if the top activity of the input stack was successfully moved to the pinned
4108 * stack.
4109 */
4110 @Override
4111 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004112 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 "moveTopActivityToPinnedStack()");
4114 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004115 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4117 + "Device doesn't support picture-in-picture mode");
4118 }
4119
4120 long ident = Binder.clearCallingIdentity();
4121 try {
Louis Chang149d5c82019-12-30 09:47:39 +08004122 return mRootWindowContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 } finally {
4124 Binder.restoreCallingIdentity(ident);
4125 }
4126 }
4127 }
4128
4129 @Override
4130 public boolean isInMultiWindowMode(IBinder token) {
4131 final long origId = Binder.clearCallingIdentity();
4132 try {
4133 synchronized (mGlobalLock) {
4134 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4135 if (r == null) {
4136 return false;
4137 }
4138 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4139 return r.inMultiWindowMode();
4140 }
4141 } finally {
4142 Binder.restoreCallingIdentity(origId);
4143 }
4144 }
4145
4146 @Override
4147 public boolean isInPictureInPictureMode(IBinder token) {
4148 final long origId = Binder.clearCallingIdentity();
4149 try {
4150 synchronized (mGlobalLock) {
4151 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4152 }
4153 } finally {
4154 Binder.restoreCallingIdentity(origId);
4155 }
4156 }
4157
4158 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004159 if (r == null || r.getRootTask() == null || !r.inPinnedWindowingMode()
4160 || r.getRootTask().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161 return false;
4162 }
4163
4164 // If we are animating to fullscreen then we have already dispatched the PIP mode
4165 // changed, so we should reflect that check here as well.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004166 final ActivityStack taskStack = r.getRootTask();
Yunfan Chen279f5582018-12-12 15:24:50 -08004167 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004168 }
4169
4170 @Override
4171 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4172 final long origId = Binder.clearCallingIdentity();
4173 try {
4174 synchronized (mGlobalLock) {
4175 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4176 "enterPictureInPictureMode", token, params);
4177
4178 // If the activity is already in picture in picture mode, then just return early
4179 if (isInPictureInPictureMode(r)) {
4180 return true;
4181 }
4182
4183 // Activity supports picture-in-picture, now check that we can enter PiP at this
4184 // point, if it is
4185 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4186 false /* beforeStopping */)) {
4187 return false;
4188 }
4189
4190 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004191 synchronized (mGlobalLock) {
Hyangseok Chaeed0624e2019-11-07 10:15:46 +09004192 if (r.getParent() == null) {
4193 Slog.e(TAG, "Skip enterPictureInPictureMode, destroyed " + r);
4194 return;
4195 }
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004196 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004197 r.setPictureInPictureParams(params);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004198 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4199 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4200 // Adjust the source bounds by the insets for the transition down
4201 final Rect sourceBounds = new Rect(
4202 r.pictureInPictureArgs.getSourceRectHint());
Louis Chang149d5c82019-12-30 09:47:39 +08004203 mRootWindowContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004204 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004205 final ActivityStack stack = r.getRootTask();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004206 stack.setPictureInPictureAspectRatio(aspectRatio);
4207 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004208 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4209 r.info.applicationInfo.uid, r.shortComponentName,
4210 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004211 logPictureInPictureArgs(params);
4212 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 };
4214
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004215 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004216 // If the keyguard is showing or occluded, then try and dismiss it before
4217 // entering picture-in-picture (this will prompt the user to authenticate if the
4218 // device is currently locked).
4219 dismissKeyguard(token, new KeyguardDismissCallback() {
4220 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004221 public void onDismissSucceeded() {
4222 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004223 }
4224 }, null /* message */);
4225 } else {
4226 // Enter picture in picture immediately otherwise
4227 enterPipRunnable.run();
4228 }
4229 return true;
4230 }
4231 } finally {
4232 Binder.restoreCallingIdentity(origId);
4233 }
4234 }
4235
4236 @Override
4237 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4238 final long origId = Binder.clearCallingIdentity();
4239 try {
4240 synchronized (mGlobalLock) {
4241 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4242 "setPictureInPictureParams", token, params);
4243
4244 // Only update the saved args from the args that are set
Robert Carrf6690d12020-02-04 14:16:21 -08004245 r.setPictureInPictureParams(params);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 if (r.inPinnedWindowingMode()) {
4247 // If the activity is already in picture-in-picture, update the pinned stack now
4248 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4249 // be used the next time the activity enters PiP
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004250 final ActivityStack stack = r.getRootTask();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 if (!stack.isAnimatingBoundsToFullscreen()) {
4252 stack.setPictureInPictureAspectRatio(
4253 r.pictureInPictureArgs.getAspectRatio());
4254 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4255 }
4256 }
4257 logPictureInPictureArgs(params);
4258 }
4259 } finally {
4260 Binder.restoreCallingIdentity(origId);
4261 }
4262 }
4263
4264 @Override
4265 public int getMaxNumPictureInPictureActions(IBinder token) {
4266 // Currently, this is a static constant, but later, we may change this to be dependent on
4267 // the context of the activity
4268 return 3;
4269 }
4270
4271 private void logPictureInPictureArgs(PictureInPictureParams params) {
4272 if (params.hasSetActions()) {
4273 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4274 params.getActions().size());
4275 }
4276 if (params.hasSetAspectRatio()) {
4277 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4278 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4279 MetricsLogger.action(lm);
4280 }
4281 }
4282
4283 /**
4284 * Checks the state of the system and the activity associated with the given {@param token} to
4285 * verify that picture-in-picture is supported for that activity.
4286 *
4287 * @return the activity record for the given {@param token} if all the checks pass.
4288 */
4289 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4290 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004291 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004292 throw new IllegalStateException(caller
4293 + ": Device doesn't support picture-in-picture mode.");
4294 }
4295
4296 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4297 if (r == null) {
4298 throw new IllegalStateException(caller
4299 + ": Can't find activity for token=" + token);
4300 }
4301
4302 if (!r.supportsPictureInPicture()) {
4303 throw new IllegalStateException(caller
4304 + ": Current activity does not support picture-in-picture.");
4305 }
4306
4307 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004308 && !mWindowManager.isValidPictureInPictureAspectRatio(
Wale Ogunwale8f93b642019-12-26 12:10:52 -08004309 r.getDisplay(), params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004310 final float minAspectRatio = mContext.getResources().getFloat(
4311 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4312 final float maxAspectRatio = mContext.getResources().getFloat(
4313 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4314 throw new IllegalArgumentException(String.format(caller
4315 + ": Aspect ratio is too extreme (must be between %f and %f).",
4316 minAspectRatio, maxAspectRatio));
4317 }
4318
4319 // Truncate the number of actions if necessary
4320 params.truncateActions(getMaxNumPictureInPictureActions(token));
4321
4322 return r;
4323 }
4324
4325 @Override
4326 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004327 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 synchronized (mGlobalLock) {
4329 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4330 if (r == null) {
4331 throw new IllegalArgumentException("Activity does not exist; token="
4332 + activityToken);
4333 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004334 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004335 }
4336 }
4337
4338 @Override
4339 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4340 Rect tempDockedTaskInsetBounds,
4341 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004342 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 long ident = Binder.clearCallingIdentity();
4344 try {
4345 synchronized (mGlobalLock) {
4346 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4347 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4348 PRESERVE_WINDOWS);
4349 }
4350 } finally {
4351 Binder.restoreCallingIdentity(ident);
4352 }
4353 }
4354
4355 @Override
4356 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004357 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004358 final long ident = Binder.clearCallingIdentity();
4359 try {
4360 synchronized (mGlobalLock) {
4361 mStackSupervisor.setSplitScreenResizing(resizing);
4362 }
4363 } finally {
4364 Binder.restoreCallingIdentity(ident);
4365 }
4366 }
4367
Evan Rosky0037e5f2019-11-05 10:26:24 -08004368 @Override
4369 public ITaskOrganizerController getTaskOrganizerController() {
4370 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS,
4371 "getTaskOrganizerController()");
4372 return mTaskOrganizerController;
4373 }
4374
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 /**
4376 * Check that we have the features required for VR-related API calls, and throw an exception if
4377 * not.
4378 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004379 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 if (!mContext.getPackageManager().hasSystemFeature(
4381 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4382 throw new UnsupportedOperationException("VR mode not supported on this device!");
4383 }
4384 }
4385
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 @Override
4387 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389
4390 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4391
4392 ActivityRecord r;
4393 synchronized (mGlobalLock) {
4394 r = ActivityRecord.isInStackLocked(token);
4395 }
4396
4397 if (r == null) {
4398 throw new IllegalArgumentException();
4399 }
4400
4401 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004402 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004403 VrManagerInternal.NO_ERROR) {
4404 return err;
4405 }
4406
4407 // Clear the binder calling uid since this path may call moveToTask().
4408 final long callingId = Binder.clearCallingIdentity();
4409 try {
4410 synchronized (mGlobalLock) {
4411 r.requestedVrComponent = (enabled) ? packageName : null;
4412
4413 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004414 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004415 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 }
4417 return 0;
4418 }
4419 } finally {
4420 Binder.restoreCallingIdentity(callingId);
4421 }
4422 }
4423
4424 @Override
4425 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4426 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4427 synchronized (mGlobalLock) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08004428 ActivityRecord activity = getTopDisplayFocusedStack().getTopNonFinishingActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004429 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4430 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4431 }
Louis Changcdec0802019-11-11 11:45:07 +08004432 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433 || activity.voiceSession != null) {
4434 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4435 return;
4436 }
4437 if (activity.pendingVoiceInteractionStart) {
4438 Slog.w(TAG, "Pending start of voice interaction already.");
4439 return;
4440 }
4441 activity.pendingVoiceInteractionStart = true;
4442 }
4443 LocalServices.getService(VoiceInteractionManagerInternal.class)
4444 .startLocalVoiceInteraction(callingActivity, options);
4445 }
4446
4447 @Override
4448 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4449 LocalServices.getService(VoiceInteractionManagerInternal.class)
4450 .stopLocalVoiceInteraction(callingActivity);
4451 }
4452
4453 @Override
4454 public boolean supportsLocalVoiceInteraction() {
4455 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4456 .supportsLocalVoiceInteraction();
4457 }
4458
4459 /** Notifies all listeners when the pinned stack animation starts. */
4460 @Override
4461 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004462 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 }
4464
4465 /** Notifies all listeners when the pinned stack animation ends. */
4466 @Override
4467 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004468 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 }
4470
4471 @Override
Wale Ogunwaleea5e87f2020-02-10 08:33:05 -08004472 public void resizePinnedStack(Rect displayedBounds, Rect configBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004473 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 final long ident = Binder.clearCallingIdentity();
4475 try {
4476 synchronized (mGlobalLock) {
Wale Ogunwaleea5e87f2020-02-10 08:33:05 -08004477 mStackSupervisor.resizePinnedStack(displayedBounds, configBounds);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004478 }
4479 } finally {
4480 Binder.restoreCallingIdentity(ident);
4481 }
4482 }
4483
4484 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004486 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487
4488 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004489 if (mWindowManager == null) {
4490 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4491 return false;
4492 }
4493
4494 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 }
4498
Riddle Hsua0022cd2019-09-09 21:12:41 +08004499 mH.sendMessage(PooledLambda.obtainMessage(
4500 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4501 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502
4503 final long origId = Binder.clearCallingIdentity();
4504 try {
4505 if (values != null) {
4506 Settings.System.clearConfiguration(values);
4507 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004508 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 UserHandle.USER_NULL, false /* deferResume */,
4510 mTmpUpdateConfigurationResult);
4511 return mTmpUpdateConfigurationResult.changes != 0;
4512 } finally {
4513 Binder.restoreCallingIdentity(origId);
4514 }
4515 }
4516 }
4517
4518 @Override
4519 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4520 CharSequence message) {
4521 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4524 }
4525 final long callingId = Binder.clearCallingIdentity();
4526 try {
4527 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004528 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004529 }
4530 } finally {
4531 Binder.restoreCallingIdentity(callingId);
4532 }
4533 }
4534
4535 @Override
4536 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004537 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 "cancelTaskWindowTransition()");
4539 final long ident = Binder.clearCallingIdentity();
4540 try {
4541 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004542 final Task task = mRootWindowContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 MATCH_TASK_IN_STACKS_ONLY);
4544 if (task == null) {
4545 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4546 return;
4547 }
Wale Ogunwale2322bed2019-10-10 17:24:19 +02004548 task.cancelTaskWindowTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 }
4550 } finally {
4551 Binder.restoreCallingIdentity(ident);
4552 }
4553 }
4554
4555 @Override
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004556 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004557 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 final long ident = Binder.clearCallingIdentity();
4559 try {
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004560 return getTaskSnapshot(taskId, isLowResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 } finally {
4562 Binder.restoreCallingIdentity(ident);
4563 }
4564 }
4565
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004566 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004567 boolean restoreFromDisk) {
Louis Changcdec0802019-11-11 11:45:07 +08004568 final Task task;
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004569 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004570 task = mRootWindowContainer.anyTaskForId(taskId,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004571 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4572 if (task == null) {
4573 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4574 return null;
4575 }
4576 }
4577 // Don't call this while holding the lock as this operation might hit the disk.
Peter Kalauskas4dc04602020-02-12 18:49:03 -08004578 return task.getSnapshot(isLowResolution, restoreFromDisk);
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004579 }
4580
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 @Override
4582 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4583 synchronized (mGlobalLock) {
4584 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4585 if (r == null) {
4586 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4587 + token);
4588 return;
4589 }
4590 final long origId = Binder.clearCallingIdentity();
4591 try {
4592 r.setDisablePreviewScreenshots(disable);
4593 } finally {
4594 Binder.restoreCallingIdentity(origId);
4595 }
4596 }
4597 }
4598
Riddle Hsu440f88b2019-11-06 22:17:35 +08004599 @Override
4600 public void invalidateHomeTaskSnapshot(IBinder token) {
4601 synchronized (mGlobalLock) {
4602 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4603 if (r == null || !r.isActivityTypeHome()) {
4604 return;
4605 }
4606 mWindowManager.mTaskSnapshotController.removeSnapshotCache(r.getTask().mTaskId);
4607 }
4608 }
4609
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004610 /** Return the user id of the last resumed activity. */
4611 @Override
4612 public @UserIdInt
4613 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004614 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4616 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004617 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004618 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004619 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004620 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004621 }
4622 }
4623
4624 @Override
4625 public void updateLockTaskFeatures(int userId, int flags) {
4626 final int callingUid = Binder.getCallingUid();
4627 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004628 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004629 "updateLockTaskFeatures()");
4630 }
4631 synchronized (mGlobalLock) {
4632 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4633 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004634 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004635 }
4636 }
4637
4638 @Override
4639 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4640 synchronized (mGlobalLock) {
4641 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4642 if (r == null) {
4643 return;
4644 }
4645 final long origId = Binder.clearCallingIdentity();
4646 try {
4647 r.setShowWhenLocked(showWhenLocked);
4648 } finally {
4649 Binder.restoreCallingIdentity(origId);
4650 }
4651 }
4652 }
4653
4654 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004655 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4656 synchronized (mGlobalLock) {
4657 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4658 if (r == null) {
4659 return;
4660 }
4661 final long origId = Binder.clearCallingIdentity();
4662 try {
4663 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4664 } finally {
4665 Binder.restoreCallingIdentity(origId);
4666 }
4667 }
4668 }
4669
4670 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004671 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4672 synchronized (mGlobalLock) {
4673 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4674 if (r == null) {
4675 return;
4676 }
4677 final long origId = Binder.clearCallingIdentity();
4678 try {
4679 r.setTurnScreenOn(turnScreenOn);
4680 } finally {
4681 Binder.restoreCallingIdentity(origId);
4682 }
4683 }
4684 }
4685
4686 @Override
4687 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004688 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004689 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004690 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004691 synchronized (mGlobalLock) {
4692 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4693 if (r == null) {
4694 return;
4695 }
4696 final long origId = Binder.clearCallingIdentity();
4697 try {
4698 r.registerRemoteAnimations(definition);
4699 } finally {
4700 Binder.restoreCallingIdentity(origId);
4701 }
4702 }
4703 }
4704
4705 @Override
Winson Chung10fc25d2019-12-10 14:13:56 -08004706 public void unregisterRemoteAnimations(IBinder token) {
4707 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4708 "unregisterRemoteAnimations");
4709 synchronized (mGlobalLock) {
4710 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4711 if (r == null) {
4712 return;
4713 }
4714 final long origId = Binder.clearCallingIdentity();
4715 try {
4716 r.unregisterRemoteAnimations();
4717 } finally {
4718 Binder.restoreCallingIdentity(origId);
4719 }
4720 }
4721 }
4722
4723 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004724 public void registerRemoteAnimationForNextActivityStart(String packageName,
4725 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004726 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004727 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004728 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004729 synchronized (mGlobalLock) {
4730 final long origId = Binder.clearCallingIdentity();
4731 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004732 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004733 packageName, adapter);
4734 } finally {
4735 Binder.restoreCallingIdentity(origId);
4736 }
4737 }
4738 }
4739
Evan Rosky966759f2019-01-15 10:33:58 -08004740 @Override
4741 public void registerRemoteAnimationsForDisplay(int displayId,
4742 RemoteAnimationDefinition definition) {
4743 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4744 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004745 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004746 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08004747 final DisplayContent display = mRootWindowContainer.getDisplayContent(displayId);
Evan Rosky966759f2019-01-15 10:33:58 -08004748 if (display == null) {
4749 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4750 return;
4751 }
4752 final long origId = Binder.clearCallingIdentity();
4753 try {
4754 display.mDisplayContent.registerRemoteAnimations(definition);
4755 } finally {
4756 Binder.restoreCallingIdentity(origId);
4757 }
4758 }
4759 }
4760
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004761 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4762 @Override
4763 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4764 synchronized (mGlobalLock) {
4765 final long origId = Binder.clearCallingIdentity();
4766 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004767 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004768 } finally {
4769 Binder.restoreCallingIdentity(origId);
4770 }
4771 }
4772 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004773
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004774 @Override
4775 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004776 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004777 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004778 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004779 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004780 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004781 }
4782 }
4783
4784 @Override
4785 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004786 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004787 != PERMISSION_GRANTED) {
4788 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4789 + Binder.getCallingPid()
4790 + ", uid=" + Binder.getCallingUid()
4791 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4792 Slog.w(TAG, msg);
4793 throw new SecurityException(msg);
4794 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004795 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004797 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004798 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004799 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004800 }
4801 }
4802
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004803 @Override
4804 public void stopAppSwitches() {
4805 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4806 synchronized (mGlobalLock) {
4807 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004808 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004809 mDidAppSwitch = false;
4810 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4811 }
4812 }
4813
4814 @Override
4815 public void resumeAppSwitches() {
4816 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4817 synchronized (mGlobalLock) {
4818 // Note that we don't execute any pending app switches... we will
4819 // let those wait until either the timeout, or the next start
4820 // activity request.
4821 mAppSwitchesAllowedTime = 0;
4822 }
4823 }
4824
Ricky Wai906af482019-06-03 17:25:28 +01004825 long getLastStopAppSwitchesTime() {
4826 return mLastStopAppSwitchesTime;
4827 }
4828
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004829 void onStartActivitySetDidAppSwitch() {
4830 if (mDidAppSwitch) {
4831 // This is the second allowed switch since we stopped switches, so now just generally
4832 // allow switches. Use case:
4833 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4834 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4835 // anyone to switch again).
4836 mAppSwitchesAllowedTime = 0;
4837 } else {
4838 mDidAppSwitch = true;
4839 }
4840 }
4841
4842 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004843 boolean shouldDisableNonVrUiLocked() {
4844 return mVrController.shouldDisableNonVrUiLocked();
4845 }
4846
Wale Ogunwale53783742018-09-16 10:21:51 -07004847 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004848 // 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 +00004849 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004850 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004851 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4852 + " to main display for VR");
Louis Chang149d5c82019-12-30 09:47:39 +08004853 mRootWindowContainer.moveStackToDisplay(
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08004854 r.getRootTaskId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004855 }
4856 mH.post(() -> {
4857 if (!mVrController.onVrModeChanged(r)) {
4858 return;
4859 }
4860 synchronized (mGlobalLock) {
4861 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4862 mWindowManager.disableNonVrUi(disableNonVrUi);
4863 if (disableNonVrUi) {
4864 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4865 // then remove the pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +08004866 mRootWindowContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004867 }
4868 }
4869 });
4870 }
4871
Wale Ogunwale53783742018-09-16 10:21:51 -07004872 @Override
4873 public int getPackageScreenCompatMode(String packageName) {
4874 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4875 synchronized (mGlobalLock) {
4876 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4877 }
4878 }
4879
4880 @Override
4881 public void setPackageScreenCompatMode(String packageName, int mode) {
4882 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4883 "setPackageScreenCompatMode");
4884 synchronized (mGlobalLock) {
4885 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4886 }
4887 }
4888
4889 @Override
4890 public boolean getPackageAskScreenCompat(String packageName) {
4891 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4892 synchronized (mGlobalLock) {
4893 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4894 }
4895 }
4896
4897 @Override
4898 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4899 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4900 "setPackageAskScreenCompat");
4901 synchronized (mGlobalLock) {
4902 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4903 }
4904 }
4905
Wale Ogunwale64258362018-10-16 15:13:37 -07004906 public static String relaunchReasonToString(int relaunchReason) {
4907 switch (relaunchReason) {
4908 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4909 return "window_resize";
4910 case RELAUNCH_REASON_FREE_RESIZE:
4911 return "free_resize";
4912 default:
4913 return null;
4914 }
4915 }
4916
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004917 ActivityStack getTopDisplayFocusedStack() {
Louis Chang149d5c82019-12-30 09:47:39 +08004918 return mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004919 }
4920
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004921 /** Pokes the task persister. */
Louis Changcdec0802019-11-11 11:45:07 +08004922 void notifyTaskPersisterLocked(Task task, boolean flush) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004923 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4924 }
4925
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004926 boolean isKeyguardLocked() {
4927 return mKeyguardController.isKeyguardLocked();
4928 }
4929
Garfield Tan01548632018-11-27 10:15:48 -08004930 /**
4931 * Clears launch params for the given package.
4932 * @param packageNames the names of the packages of which the launch params are to be cleared
4933 */
4934 @Override
4935 public void clearLaunchParamsForPackages(List<String> packageNames) {
4936 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4937 "clearLaunchParamsForPackages");
4938 synchronized (mGlobalLock) {
4939 for (int i = 0; i < packageNames.size(); ++i) {
4940 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4941 }
4942 }
4943 }
4944
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004945 /**
4946 * Makes the display with the given id a single task instance display. I.e the display can only
4947 * contain one task.
4948 */
4949 @Override
4950 public void setDisplayToSingleTaskInstance(int displayId) {
4951 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4952 "setDisplayToSingleTaskInstance");
4953 final long origId = Binder.clearCallingIdentity();
4954 try {
Louis Chang677921f2019-12-06 16:44:24 +08004955 final DisplayContent display =
Louis Chang149d5c82019-12-30 09:47:39 +08004956 mRootWindowContainer.getDisplayContentOrCreate(displayId);
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004957 if (display != null) {
4958 display.setDisplayToSingleTaskInstance();
4959 }
4960 } finally {
4961 Binder.restoreCallingIdentity(origId);
4962 }
4963 }
4964
jorgegil@google.com06bc3232019-10-31 14:51:22 -07004965 /**
4966 * Requests that an activity should enter picture-in-picture mode if possible.
4967 */
4968 @Override
4969 public void requestPictureInPictureMode(IBinder token) throws RemoteException {
4970 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4971 "requestPictureInPictureMode");
4972 final long origId = Binder.clearCallingIdentity();
4973 try {
4974 synchronized (mGlobalLock) {
4975 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
4976 if (activity == null) {
4977 return;
4978 }
4979
4980 final boolean canEnterPictureInPicture = activity.checkEnterPictureInPictureState(
4981 "requestPictureInPictureMode", /* beforeStopping */ false);
4982 if (!canEnterPictureInPicture) {
4983 throw new IllegalStateException(
4984 "Requested PIP on an activity that doesn't support it");
4985 }
4986
4987 try {
4988 final ClientTransaction transaction = ClientTransaction.obtain(
4989 activity.app.getThread(),
4990 activity.token);
4991 transaction.addCallback(EnterPipRequestedItem.obtain());
4992 getLifecycleManager().scheduleTransaction(transaction);
4993 } catch (Exception e) {
4994 Slog.w(TAG, "Failed to send enter pip requested item: "
4995 + activity.intent.getComponent(), e);
4996 }
4997 }
4998 } finally {
4999 Binder.restoreCallingIdentity(origId);
5000 }
5001 }
5002
Wale Ogunwale31913b52018-10-13 08:29:31 -07005003 void dumpLastANRLocked(PrintWriter pw) {
5004 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
5005 if (mLastANRState == null) {
5006 pw.println(" <no ANR has occurred since boot>");
5007 } else {
5008 pw.println(mLastANRState);
5009 }
5010 }
5011
5012 void dumpLastANRTracesLocked(PrintWriter pw) {
5013 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
5014
5015 final File[] files = new File(ANR_TRACE_DIR).listFiles();
5016 if (ArrayUtils.isEmpty(files)) {
5017 pw.println(" <no ANR has occurred since boot>");
5018 return;
5019 }
5020 // Find the latest file.
5021 File latest = null;
5022 for (File f : files) {
5023 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
5024 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005025 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005026 }
5027 pw.print("File: ");
5028 pw.print(latest.getName());
5029 pw.println();
5030 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
5031 String line;
5032 while ((line = in.readLine()) != null) {
5033 pw.println(line);
5034 }
5035 } catch (IOException e) {
5036 pw.print("Unable to read: ");
5037 pw.print(e);
5038 pw.println();
5039 }
5040 }
5041
5042 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5043 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
5044 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
5045 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
5046 }
5047
5048 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5049 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
5050 pw.println(header);
5051
Louis Chang149d5c82019-12-30 09:47:39 +08005052 boolean printedAnything = mRootWindowContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005053 dumpPackage);
5054 boolean needSep = printedAnything;
5055
5056 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Louis Chang149d5c82019-12-30 09:47:39 +08005057 mRootWindowContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005058 " ResumedActivity: ");
5059 if (printed) {
5060 printedAnything = true;
5061 needSep = false;
5062 }
5063
5064 if (dumpPackage == null) {
5065 if (needSep) {
5066 pw.println();
5067 }
5068 printedAnything = true;
5069 mStackSupervisor.dump(pw, " ");
5070 }
5071
5072 if (!printedAnything) {
5073 pw.println(" (nothing)");
5074 }
5075 }
5076
5077 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08005078 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Louis Chang149d5c82019-12-30 09:47:39 +08005079 mRootWindowContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07005080 pw.println(" ");
5081 }
5082
5083 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5084 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5085 getActivityStartController().dump(pw, "", dumpPackage);
5086 }
5087
5088 /**
5089 * There are three things that cmd can be:
5090 * - a flattened component name that matches an existing activity
5091 * - the cmd arg isn't the flattened component name of an existing activity:
5092 * dump all activity whose component contains the cmd as a substring
5093 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005094 * <p>
5095 * The caller should not hold lock when calling this method because it will wait for the
5096 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07005097 *
5098 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5099 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5100 */
5101 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5102 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5103 ArrayList<ActivityRecord> activities;
5104
5105 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08005106 activities = mRootWindowContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005107 dumpFocusedStackOnly);
5108 }
5109
5110 if (activities.size() <= 0) {
5111 return false;
5112 }
5113
5114 String[] newArgs = new String[args.length - opti];
5115 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5116
Louis Changcdec0802019-11-11 11:45:07 +08005117 Task lastTask = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005118 boolean needSep = false;
5119 for (int i = activities.size() - 1; i >= 0; i--) {
5120 ActivityRecord r = activities.get(i);
5121 if (needSep) {
5122 pw.println();
5123 }
5124 needSep = true;
5125 synchronized (mGlobalLock) {
Louis Changcdec0802019-11-11 11:45:07 +08005126 final Task task = r.getTask();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005127 if (lastTask != task) {
5128 lastTask = task;
5129 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07005130 pw.print(" id="); pw.print(lastTask.mTaskId);
5131 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005132 if (dumpAll) {
5133 lastTask.dump(pw, " ");
5134 }
5135 }
5136 }
5137 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5138 }
5139 return true;
5140 }
5141
5142 /**
5143 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5144 * there is a thread associated with the activity.
5145 */
5146 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5147 final ActivityRecord r, String[] args, boolean dumpAll) {
5148 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005149 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07005150 synchronized (mGlobalLock) {
5151 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5152 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5153 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005154 if (r.hasProcess()) {
5155 pw.println(r.app.getPid());
5156 appThread = r.app.getThread();
5157 } else {
5158 pw.println("(not running)");
5159 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005160 if (dumpAll) {
Garfield Tane8d84ab2019-10-11 09:49:40 -07005161 r.dump(pw, innerPrefix, true /* dumpAll */);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005162 }
5163 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005164 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005165 // flush anything that is already in the PrintWriter since the thread is going
5166 // to write to the file descriptor directly
5167 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005168 try (TransferPipe tp = new TransferPipe()) {
5169 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5170 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005171 } catch (IOException e) {
5172 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5173 } catch (RemoteException e) {
5174 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5175 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005176 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005177 }
5178
sanryhuang498e77e2018-12-06 14:57:01 +08005179 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5180 boolean testPssMode) {
5181 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5182 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5183 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Louis Chang149d5c82019-12-30 09:47:39 +08005184 for (ActivityTaskManagerInternal.SleepToken st : mRootWindowContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005185 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5186 st.toString());
5187 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005188 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5189 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5190 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005191 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5192 testPssMode);
5193 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005194 }
5195
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196 int getCurrentUserId() {
5197 return mAmInternal.getCurrentUserId();
5198 }
5199
5200 private void enforceNotIsolatedCaller(String caller) {
5201 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5202 throw new SecurityException("Isolated process not allowed to call " + caller);
5203 }
5204 }
5205
Wale Ogunwalef6733932018-06-27 05:14:34 -07005206 public Configuration getConfiguration() {
5207 Configuration ci;
5208 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005209 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005210 ci.userSetLocale = false;
5211 }
5212 return ci;
5213 }
5214
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215 /**
5216 * Current global configuration information. Contains general settings for the entire system,
5217 * also corresponds to the merged configuration of the default display.
5218 */
5219 Configuration getGlobalConfiguration() {
Louis Chang149d5c82019-12-30 09:47:39 +08005220 // Return default configuration before mRootWindowContainer initialized, which happens
Louis Chang3ff72a82019-12-17 12:12:59 +08005221 // while initializing process record for system, see {@link
5222 // ActivityManagerService#setSystemProcess}.
Louis Chang149d5c82019-12-30 09:47:39 +08005223 return mRootWindowContainer != null ? mRootWindowContainer.getConfiguration()
Louis Chang3ff72a82019-12-17 12:12:59 +08005224 : new Configuration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
5226
5227 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5228 boolean initLocale) {
5229 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5230 }
5231
5232 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5233 boolean initLocale, boolean deferResume) {
5234 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5235 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5236 UserHandle.USER_NULL, deferResume);
5237 }
5238
Wale Ogunwale59507092018-10-29 09:00:30 -07005239 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240 final long origId = Binder.clearCallingIdentity();
5241 try {
5242 synchronized (mGlobalLock) {
5243 updateConfigurationLocked(values, null, false, true, userId,
5244 false /* deferResume */);
5245 }
5246 } finally {
5247 Binder.restoreCallingIdentity(origId);
5248 }
5249 }
5250
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5252 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5253 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5254 deferResume, null /* result */);
5255 }
5256
5257 /**
5258 * Do either or both things: (1) change the current configuration, and (2)
5259 * make sure the given activity is running with the (now) current
5260 * configuration. Returns true if the activity has been left running, or
5261 * false if <var>starting</var> is being destroyed to match the new
5262 * configuration.
5263 *
5264 * @param userId is only used when persistent parameter is set to true to persist configuration
5265 * for that particular user
5266 */
5267 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5268 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5269 ActivityTaskManagerService.UpdateConfigurationResult result) {
5270 int changes = 0;
5271 boolean kept = true;
5272
Riddle Hsua0022cd2019-09-09 21:12:41 +08005273 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005274 try {
5275 if (values != null) {
5276 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5277 deferResume);
5278 }
5279
5280 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5281 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005282 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005283 }
5284
5285 if (result != null) {
5286 result.changes = changes;
5287 result.activityRelaunched = !kept;
5288 }
5289 return kept;
5290 }
5291
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005293 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005295
Louis Chang677921f2019-12-06 16:44:24 +08005296 final DisplayContent defaultDisplay =
Louis Chang149d5c82019-12-30 09:47:39 +08005297 mRootWindowContainer.getDisplayContent(DEFAULT_DISPLAY);
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005299 mTempConfig.setTo(getGlobalConfiguration());
5300 final int changes = mTempConfig.updateFrom(values);
5301 if (changes == 0) {
5302 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5303 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5304 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5305 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005306 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307 return 0;
5308 }
5309
5310 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5311 "Updating global configuration to: " + values);
Jeff Changd136e772019-11-05 20:33:52 +08005312 writeConfigurationChanged(changes);
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005313 FrameworkStatsLog.write(FrameworkStatsLog.RESOURCE_CONFIGURATION_CHANGED,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005314 values.colorMode,
5315 values.densityDpi,
5316 values.fontScale,
5317 values.hardKeyboardHidden,
5318 values.keyboard,
5319 values.keyboardHidden,
5320 values.mcc,
5321 values.mnc,
5322 values.navigation,
5323 values.navigationHidden,
5324 values.orientation,
5325 values.screenHeightDp,
5326 values.screenLayout,
5327 values.screenWidthDp,
5328 values.smallestScreenWidthDp,
5329 values.touchscreen,
5330 values.uiMode);
5331
5332
5333 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5334 final LocaleList locales = values.getLocales();
5335 int bestLocaleIndex = 0;
5336 if (locales.size() > 1) {
5337 if (mSupportedSystemLocales == null) {
5338 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5339 }
5340 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5341 }
5342 SystemProperties.set("persist.sys.locale",
5343 locales.get(bestLocaleIndex).toLanguageTag());
5344 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005345
5346 final Message m = PooledLambda.obtainMessage(
5347 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5348 locales.get(bestLocaleIndex));
5349 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005350 }
5351
Yunfan Chen75157d72018-07-27 14:47:21 +09005352 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005353
5354 // Update stored global config and notify everyone about the change.
Louis Chang149d5c82019-12-30 09:47:39 +08005355 mRootWindowContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005356
5357 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5358 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005359 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005360
5361 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005362 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005363
5364 AttributeCache ac = AttributeCache.instance();
5365 if (ac != null) {
5366 ac.updateConfiguration(mTempConfig);
5367 }
5368
5369 // Make sure all resources in our process are updated right now, so that anyone who is going
5370 // to retrieve resource values after we return will be sure to get the new ones. This is
5371 // especially important during boot, where the first config change needs to guarantee all
5372 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005373 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005374
5375 // We need another copy of global config because we're scheduling some calls instead of
5376 // running them in place. We need to be sure that object we send will be handled unchanged.
5377 final Configuration configCopy = new Configuration(mTempConfig);
5378 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005379 final Message msg = PooledLambda.obtainMessage(
5380 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5381 this, userId, configCopy);
5382 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005383 }
5384
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005385 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5386 for (int i = pidMap.size() - 1; i >= 0; i--) {
5387 final int pid = pidMap.keyAt(i);
5388 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005389 if (DEBUG_CONFIGURATION) {
5390 Slog.v(TAG_CONFIGURATION, "Update process config of "
5391 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005392 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005393 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005394 }
5395
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005396 final Message msg = PooledLambda.obtainMessage(
5397 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5398 mAmInternal, changes, initLocale);
5399 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005400
5401 // Override configuration of the default display duplicates global config, so we need to
5402 // update it also. This will also notify WindowManager about changes.
Louis Chang149d5c82019-12-30 09:47:39 +08005403 defaultDisplay.performDisplayOverrideConfigUpdate(mRootWindowContainer.getConfiguration(),
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005404 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005405
5406 return changes;
5407 }
5408
Riddle Hsua0022cd2019-09-09 21:12:41 +08005409 /** @see WindowSurfacePlacer#deferLayout */
5410 void deferWindowLayout() {
5411 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5412 // Reset the reasons at the first entrance because we only care about the changes in the
5413 // deferred scope.
5414 mLayoutReasons = 0;
5415 }
5416
5417 mWindowManager.mWindowPlacerLocked.deferLayout();
5418 }
5419
5420 /** @see WindowSurfacePlacer#continueLayout */
5421 void continueWindowLayout() {
5422 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5423 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5424 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5425 }
5426 }
5427
5428 /**
5429 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5430 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5431 * defer count is gone.
5432 */
5433 void addWindowLayoutReasons(@LayoutReason int reasons) {
5434 mLayoutReasons |= reasons;
5435 }
5436
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 private void updateEventDispatchingLocked(boolean booted) {
5438 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5439 }
5440
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005441 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5442 final ContentResolver resolver = mContext.getContentResolver();
5443 Settings.System.putConfigurationForUser(resolver, config, userId);
5444 }
5445
5446 private void sendLocaleToMountDaemonMsg(Locale l) {
5447 try {
5448 IBinder service = ServiceManager.getService("mount");
5449 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5450 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5451 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5452 } catch (RemoteException e) {
5453 Log.e(TAG, "Error storing locale for decryption UI", e);
5454 }
5455 }
5456
Alison Cichowlas3e340502018-08-07 17:15:01 -04005457 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5458 mStartActivitySources.remove(permissionToken);
5459 mExpiredStartAsCallerTokens.add(permissionToken);
5460 }
5461
5462 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5463 mExpiredStartAsCallerTokens.remove(permissionToken);
5464 }
5465
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005466 boolean isActivityStartsLoggingEnabled() {
5467 return mAmInternal.isActivityStartsLoggingEnabled();
5468 }
5469
Michal Karpinski8596ded2018-11-14 14:43:48 +00005470 boolean isBackgroundActivityStartsEnabled() {
5471 return mAmInternal.isBackgroundActivityStartsEnabled();
5472 }
5473
Wale Ogunwalef6733932018-06-27 05:14:34 -07005474 void enableScreenAfterBoot(boolean booted) {
Jeff Changd136e772019-11-05 20:33:52 +08005475 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005476 mWindowManager.enableScreenAfterBoot();
5477
5478 synchronized (mGlobalLock) {
5479 updateEventDispatchingLocked(booted);
5480 }
5481 }
5482
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005483 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5484 if (r == null || !r.hasProcess()) {
5485 return KEY_DISPATCHING_TIMEOUT_MS;
5486 }
5487 return getInputDispatchingTimeoutLocked(r.app);
5488 }
5489
5490 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005491 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005492 }
5493
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494 /**
5495 * Decide based on the configuration whether we should show the ANR,
5496 * crash, etc dialogs. The idea is that if there is no affordance to
5497 * press the on-screen buttons, or the user experience would be more
5498 * greatly impacted than the crash itself, we shouldn't show the dialog.
5499 *
5500 * A thought: SystemUI might also want to get told about this, the Power
5501 * dialog / global actions also might want different behaviors.
5502 */
5503 private void updateShouldShowDialogsLocked(Configuration config) {
5504 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5505 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5506 && config.navigation == Configuration.NAVIGATION_NONAV);
5507 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5508 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5509 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5510 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5511 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5512 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5513 HIDE_ERROR_DIALOGS, 0) != 0;
5514 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5515 }
5516
5517 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5518 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5519 FONT_SCALE, 1.0f, userId);
5520
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005521 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005522 if (getGlobalConfiguration().fontScale == scaleFactor) {
5523 return;
5524 }
5525
5526 final Configuration configuration
5527 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5528 configuration.fontScale = scaleFactor;
5529 updatePersistentConfiguration(configuration, userId);
5530 }
5531 }
5532
5533 // Actually is sleeping or shutting down or whatever else in the future
5534 // is an inactive state.
5535 boolean isSleepingOrShuttingDownLocked() {
5536 return isSleepingLocked() || mShuttingDown;
5537 }
5538
5539 boolean isSleepingLocked() {
5540 return mSleeping;
5541 }
5542
Riddle Hsu16567132018-08-16 21:37:47 +08005543 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Louis Changcdec0802019-11-11 11:45:07 +08005545 final Task task = r.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546 if (task.isActivityTypeStandard()) {
5547 if (mCurAppTimeTracker != r.appTimeTracker) {
5548 // We are switching app tracking. Complete the current one.
5549 if (mCurAppTimeTracker != null) {
5550 mCurAppTimeTracker.stop();
5551 mH.obtainMessage(
5552 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Louis Chang149d5c82019-12-30 09:47:39 +08005553 mRootWindowContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005554 mCurAppTimeTracker = null;
5555 }
5556 if (r.appTimeTracker != null) {
5557 mCurAppTimeTracker = r.appTimeTracker;
5558 startTimeTrackingFocusedActivityLocked();
5559 }
5560 } else {
5561 startTimeTrackingFocusedActivityLocked();
5562 }
5563 } else {
5564 r.appTimeTracker = null;
5565 }
5566 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5567 // TODO: Probably not, because we don't want to resume voice on switching
5568 // back to this activity
5569 if (task.voiceInteractor != null) {
5570 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5571 } else {
5572 finishRunningVoiceLocked();
5573
5574 if (mLastResumedActivity != null) {
5575 final IVoiceInteractionSession session;
5576
Louis Changcdec0802019-11-11 11:45:07 +08005577 final Task lastResumedActivityTask = mLastResumedActivity.getTask();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005578 if (lastResumedActivityTask != null
5579 && lastResumedActivityTask.voiceSession != null) {
5580 session = lastResumedActivityTask.voiceSession;
5581 } else {
5582 session = mLastResumedActivity.voiceSession;
5583 }
5584
5585 if (session != null) {
5586 // We had been in a voice interaction session, but now focused has
5587 // move to something different. Just finish the session, we can't
5588 // return to it and retain the proper state and synchronization with
5589 // the voice interaction service.
5590 finishVoiceTask(session);
5591 }
5592 }
5593 }
5594
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005595 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5596 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597 }
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005598 final Task prevTask = mLastResumedActivity != null ? mLastResumedActivity.getTask() : null;
5599
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600 updateResumedAppTrace(r);
5601 mLastResumedActivity = r;
5602
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005603 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005604
Bogyun Sonbfb64dc2019-12-09 17:50:24 +09005605 if (prevTask == null || task != prevTask) {
5606 if (prevTask != null) {
5607 mTaskChangeNotificationController.notifyTaskFocusChanged(prevTask.mTaskId, false);
5608 }
5609 mTaskChangeNotificationController.notifyTaskFocusChanged(task.mTaskId, true);
5610 }
5611
Wale Ogunwalef6733932018-06-27 05:14:34 -07005612 applyUpdateLockStateLocked(r);
5613 applyUpdateVrModeLocked(r);
5614
Jeff Changd136e772019-11-05 20:33:52 +08005615 EventLogTags.writeWmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005616 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005617 r == null ? "NULL" : r.shortComponentName,
5618 reason);
5619 }
5620
5621 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5622 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005623 final ActivityTaskManagerInternal.SleepToken token =
Louis Chang149d5c82019-12-30 09:47:39 +08005624 mRootWindowContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005625 updateSleepIfNeededLocked();
5626 return token;
5627 }
5628 }
5629
5630 void updateSleepIfNeededLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005631 final boolean shouldSleep = !mRootWindowContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005632 final boolean wasSleeping = mSleeping;
5633 boolean updateOomAdj = false;
5634
5635 if (!shouldSleep) {
5636 // If wasSleeping is true, we need to wake up activity manager state from when
5637 // we started sleeping. In either case, we need to apply the sleep tokens, which
5638 // will wake up stacks or put them to sleep as appropriate.
5639 if (wasSleeping) {
5640 mSleeping = false;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005641 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5642 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005643 startTimeTrackingFocusedActivityLocked();
5644 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005645 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005646 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5647 }
Louis Chang149d5c82019-12-30 09:47:39 +08005648 mRootWindowContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005649 if (wasSleeping) {
5650 updateOomAdj = true;
5651 }
5652 } else if (!mSleeping && shouldSleep) {
5653 mSleeping = true;
Muhammad Qureshi759f92f2020-01-28 10:41:55 -08005654 FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5655 FrameworkStatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005656 if (mCurAppTimeTracker != null) {
5657 mCurAppTimeTracker.stop();
5658 }
5659 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005660 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005661 mStackSupervisor.goingToSleepLocked();
5662 updateResumedAppTrace(null /* resumed */);
5663 updateOomAdj = true;
5664 }
5665 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005666 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005667 }
5668 }
5669
5670 void updateOomAdj() {
Wale Ogunwalea38654f2019-11-17 20:37:15 -08005671 mH.removeCallbacks(mUpdateOomAdjRunnable);
5672 mH.post(mUpdateOomAdjRunnable);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005673 }
5674
Wale Ogunwale53783742018-09-16 10:21:51 -07005675 void updateCpuStats() {
5676 mH.post(mAmInternal::updateCpuStats);
5677 }
5678
Hui Yu03d12402018-12-06 18:00:37 -08005679 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5680 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005681 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5682 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005683 mH.sendMessage(m);
5684 }
5685
Hui Yu03d12402018-12-06 18:00:37 -08005686 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005687 ComponentName taskRoot = null;
Louis Changcdec0802019-11-11 11:45:07 +08005688 final Task task = activity.getTask();
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005689 if (task != null) {
5690 final ActivityRecord rootActivity = task.getRootActivity();
5691 if (rootActivity != null) {
5692 taskRoot = rootActivity.mActivityComponent;
5693 }
5694 }
5695
Hui Yu03d12402018-12-06 18:00:37 -08005696 final Message m = PooledLambda.obtainMessage(
5697 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005698 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005699 mH.sendMessage(m);
5700 }
5701
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005702 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5703 String hostingType) {
5704 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005705 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
5706 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005707 + activity.processName);
5708 }
5709 // Post message to start process to avoid possible deadlock of calling into AMS with the
5710 // ATMS lock held.
5711 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5712 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5713 isTop, hostingType, activity.intent.getComponent());
5714 mH.sendMessage(m);
5715 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005716 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005717 }
5718 }
5719
Wale Ogunwale53783742018-09-16 10:21:51 -07005720 void setBooting(boolean booting) {
5721 mAmInternal.setBooting(booting);
5722 }
5723
5724 boolean isBooting() {
5725 return mAmInternal.isBooting();
5726 }
5727
5728 void setBooted(boolean booted) {
5729 mAmInternal.setBooted(booted);
5730 }
5731
5732 boolean isBooted() {
5733 return mAmInternal.isBooted();
5734 }
5735
5736 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5737 mH.post(() -> {
5738 if (finishBooting) {
5739 mAmInternal.finishBooting();
5740 }
5741 if (enableScreen) {
5742 mInternal.enableScreenAfterBoot(isBooted());
5743 }
5744 });
5745 }
5746
5747 void setHeavyWeightProcess(ActivityRecord root) {
5748 mHeavyWeightProcess = root.app;
5749 final Message m = PooledLambda.obtainMessage(
5750 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005751 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005752 mH.sendMessage(m);
5753 }
5754
5755 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5756 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5757 return;
5758 }
5759
5760 mHeavyWeightProcess = null;
5761 final Message m = PooledLambda.obtainMessage(
5762 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5763 proc.mUserId);
5764 mH.sendMessage(m);
5765 }
5766
5767 private void cancelHeavyWeightProcessNotification(int userId) {
5768 final INotificationManager inm = NotificationManager.getService();
5769 if (inm == null) {
5770 return;
5771 }
5772 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005773 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005774 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5775 } catch (RuntimeException e) {
5776 Slog.w(TAG, "Error canceling notification for service", e);
5777 } catch (RemoteException e) {
5778 }
5779
5780 }
5781
5782 private void postHeavyWeightProcessNotification(
5783 WindowProcessController proc, Intent intent, int userId) {
5784 if (proc == null) {
5785 return;
5786 }
5787
5788 final INotificationManager inm = NotificationManager.getService();
5789 if (inm == null) {
5790 return;
5791 }
5792
5793 try {
5794 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5795 String text = mContext.getString(R.string.heavy_weight_notification,
5796 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5797 Notification notification =
5798 new Notification.Builder(context,
5799 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5800 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5801 .setWhen(0)
5802 .setOngoing(true)
5803 .setTicker(text)
5804 .setColor(mContext.getColor(
5805 com.android.internal.R.color.system_notification_accent_color))
5806 .setContentTitle(text)
5807 .setContentText(
5808 mContext.getText(R.string.heavy_weight_notification_detail))
5809 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5810 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5811 new UserHandle(userId)))
5812 .build();
5813 try {
5814 inm.enqueueNotificationWithTag("android", "android", null,
5815 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5816 } catch (RuntimeException e) {
5817 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5818 } catch (RemoteException e) {
5819 }
5820 } catch (PackageManager.NameNotFoundException e) {
5821 Slog.w(TAG, "Unable to create context for heavy notification", e);
5822 }
5823
5824 }
5825
Philip P. Moltmannee295092020-02-10 08:46:26 -08005826 IIntentSender getIntentSenderLocked(int type, String packageName, String featureId,
5827 int callingUid, int userId, IBinder token, String resultWho, int requestCode,
5828 Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005829
5830 ActivityRecord activity = null;
5831 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5832 activity = ActivityRecord.isInStackLocked(token);
5833 if (activity == null) {
5834 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5835 return null;
5836 }
5837 if (activity.finishing) {
5838 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5839 return null;
5840 }
5841 }
5842
5843 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08005844 featureId, callingUid, userId, token, resultWho, requestCode, intents,
5845 resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005846 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5847 if (noCreate) {
5848 return rec;
5849 }
5850 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5851 if (activity.pendingResults == null) {
5852 activity.pendingResults = new HashSet<>();
5853 }
5854 activity.pendingResults.add(rec.ref);
5855 }
5856 return rec;
5857 }
5858
Andrii Kulian52d255c2018-07-13 11:32:19 -07005859 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005860 private void startTimeTrackingFocusedActivityLocked() {
Louis Chang149d5c82019-12-30 09:47:39 +08005861 final ActivityRecord resumedActivity = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005862 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5863 mCurAppTimeTracker.start(resumedActivity.packageName);
5864 }
5865 }
5866
5867 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5868 if (mTracedResumedActivity != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005869 Trace.asyncTraceEnd(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005870 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5871 }
5872 if (resumed != null) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08005873 Trace.asyncTraceBegin(TRACE_TAG_WINDOW_MANAGER,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005874 constructResumedTraceName(resumed.packageName), 0);
5875 }
5876 mTracedResumedActivity = resumed;
5877 }
5878
5879 private String constructResumedTraceName(String packageName) {
5880 return "focused app: " + packageName;
5881 }
5882
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005883 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005884 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005885 boolean kept = true;
Louis Chang149d5c82019-12-30 09:47:39 +08005886 final ActivityStack mainStack = mRootWindowContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005887 // mainStack is null during startup.
5888 if (mainStack != null) {
5889 if (changes != 0 && starting == null) {
5890 // If the configuration changed, and the caller is not already
5891 // in the process of starting an activity, then find the top
5892 // activity to check if its configuration needs to change.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09005893 starting = mainStack.topRunningActivity();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005894 }
5895
5896 if (starting != null) {
5897 kept = starting.ensureActivityConfiguration(changes,
5898 false /* preserveWindow */);
5899 // And we need to make sure at this point that all other activities
5900 // are made visible with the correct configuration.
Louis Chang149d5c82019-12-30 09:47:39 +08005901 mRootWindowContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005902 !PRESERVE_WINDOWS);
5903 }
5904 }
5905
5906 return kept;
5907 }
5908
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005909 void scheduleAppGcsLocked() {
5910 mH.post(() -> mAmInternal.scheduleAppGcs());
5911 }
5912
Wale Ogunwale53783742018-09-16 10:21:51 -07005913 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5914 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5915 }
5916
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005917 /**
5918 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5919 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5920 * on demand.
5921 */
5922 IPackageManager getPackageManager() {
5923 return AppGlobals.getPackageManager();
5924 }
5925
5926 PackageManagerInternal getPackageManagerInternalLocked() {
5927 if (mPmInternal == null) {
5928 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5929 }
5930 return mPmInternal;
5931 }
5932
Hai Zhangf4da9be2019-05-01 13:46:06 +08005933 PermissionPolicyInternal getPermissionPolicyInternal() {
5934 if (mPermissionPolicyInternal == null) {
5935 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5936 }
5937 return mPermissionPolicyInternal;
5938 }
5939
Wale Ogunwale008163e2018-07-23 23:11:08 -07005940 AppWarnings getAppWarningsLocked() {
5941 return mAppWarnings;
5942 }
5943
Wale Ogunwale214f3482018-10-04 11:00:47 -07005944 Intent getHomeIntent() {
5945 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5946 intent.setComponent(mTopComponent);
5947 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5948 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5949 intent.addCategory(Intent.CATEGORY_HOME);
5950 }
5951 return intent;
5952 }
5953
Chilun2ef71f72018-11-16 17:57:15 +08005954 /**
5955 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5956 * activities.
5957 *
5958 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5959 * component defined in config_secondaryHomeComponent.
5960 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5961 */
5962 Intent getSecondaryHomeIntent(String preferredPackage) {
5963 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005964 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5965 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5966 if (preferredPackage == null || useSystemProvidedLauncher) {
5967 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005968 final String secondaryHomeComponent = mContext.getResources().getString(
5969 com.android.internal.R.string.config_secondaryHomeComponent);
5970 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5971 } else {
5972 intent.setPackage(preferredPackage);
5973 }
5974 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5975 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5976 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5977 }
5978 return intent;
5979 }
5980
Wale Ogunwale214f3482018-10-04 11:00:47 -07005981 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5982 if (info == null) return null;
5983 ApplicationInfo newInfo = new ApplicationInfo(info);
5984 newInfo.initForUser(userId);
5985 return newInfo;
5986 }
5987
Wale Ogunwale9c103022018-10-18 07:44:54 -07005988 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005989 if (uid == SYSTEM_UID) {
5990 // The system gets to run in any process. If there are multiple processes with the same
5991 // uid, just pick the first (this should never happen).
5992 final SparseArray<WindowProcessController> procs =
5993 mProcessNames.getMap().get(processName);
5994 if (procs == null) return null;
5995 final int procCount = procs.size();
5996 for (int i = 0; i < procCount; i++) {
5997 final int procUid = procs.keyAt(i);
5998 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5999 // Don't use an app process or different user process for system component.
6000 continue;
6001 }
6002 return procs.valueAt(i);
6003 }
6004 }
6005
6006 return mProcessNames.get(processName, uid);
6007 }
6008
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006009 WindowProcessController getProcessController(IApplicationThread thread) {
6010 if (thread == null) {
6011 return null;
6012 }
6013
6014 final IBinder threadBinder = thread.asBinder();
6015 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
6016 for (int i = pmap.size()-1; i >= 0; i--) {
6017 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
6018 for (int j = procs.size() - 1; j >= 0; j--) {
6019 final WindowProcessController proc = procs.valueAt(j);
6020 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
6021 return proc;
6022 }
6023 }
6024 }
6025
6026 return null;
6027 }
6028
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006029 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006030 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09006031 if (proc == null) return null;
6032 if (UserHandle.isApp(uid) && proc.mUid == uid) {
6033 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00006034 }
6035 return null;
6036 }
6037
Riddle Hsua0536432019-02-16 00:38:59 +08006038 int getUidState(int uid) {
6039 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006040 }
6041
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006042 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01006043 // A uid is considered to be foreground if it has a visible non-toast window.
6044 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00006045 }
6046
Ricky Wai96f5c352019-04-10 18:40:17 +01006047 boolean isDeviceOwner(int uid) {
6048 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006049 }
6050
Ricky Wai96f5c352019-04-10 18:40:17 +01006051 void setDeviceOwnerUid(int uid) {
6052 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00006053 }
6054
Wale Ogunwale9de19442018-10-18 19:05:03 -07006055 /**
6056 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6057 * the whitelist
6058 */
6059 String getPendingTempWhitelistTagForUidLocked(int uid) {
6060 return mPendingTempWhitelist.get(uid);
6061 }
6062
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006063 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
6064 if (true || Build.IS_USER) {
6065 return;
6066 }
6067
6068 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6069 StrictMode.allowThreadDiskWrites();
6070 try {
6071 File tracesDir = new File("/data/anr");
6072 File tracesFile = null;
6073 try {
6074 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6075
6076 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01006077 String timeString =
6078 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
6079 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006080 sb.append(": ");
6081 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6082 sb.append(" since ");
6083 sb.append(msg);
6084 FileOutputStream fos = new FileOutputStream(tracesFile);
6085 fos.write(sb.toString().getBytes());
6086 if (app == null) {
6087 fos.write("\n*** No application process!".getBytes());
6088 }
6089 fos.close();
6090 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6091 } catch (IOException e) {
6092 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6093 return;
6094 }
6095
6096 if (app != null && app.getPid() > 0) {
6097 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6098 firstPids.add(app.getPid());
6099 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6100 }
6101
6102 File lastTracesFile = null;
6103 File curTracesFile = null;
6104 for (int i=9; i>=0; i--) {
6105 String name = String.format(Locale.US, "slow%02d.txt", i);
6106 curTracesFile = new File(tracesDir, name);
6107 if (curTracesFile.exists()) {
6108 if (lastTracesFile != null) {
6109 curTracesFile.renameTo(lastTracesFile);
6110 } else {
6111 curTracesFile.delete();
6112 }
6113 }
6114 lastTracesFile = curTracesFile;
6115 }
6116 tracesFile.renameTo(curTracesFile);
6117 } finally {
6118 StrictMode.setThreadPolicy(oldPolicy);
6119 }
6120 }
6121
Michal Karpinskida34cd42019-04-02 19:46:52 +01006122 boolean isAssociatedCompanionApp(int userId, int uid) {
6123 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6124 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006125 return false;
6126 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006127 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006128 }
6129
Issei Suzuki734bc942019-06-05 13:59:52 +02006130 void notifySingleTaskDisplayEmpty(int displayId) {
6131 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
6132 }
6133
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006134 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006135 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006136
6137
Wale Ogunwale98875612018-10-12 07:53:02 -07006138 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6139 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006140
Riddle Hsud93a6c42018-11-29 21:50:06 +08006141 H(Looper looper) {
6142 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006143 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006144
6145 @Override
6146 public void handleMessage(Message msg) {
6147 switch (msg.what) {
6148 case REPORT_TIME_TRACKER_MSG: {
6149 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6150 tracker.deliverResult(mContext);
6151 } break;
6152 }
6153 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006154 }
6155
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006156 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006157 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006158
6159 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006160 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006161 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006162
6163 @Override
6164 public void handleMessage(Message msg) {
6165 switch (msg.what) {
6166 case DISMISS_DIALOG_UI_MSG: {
6167 final Dialog d = (Dialog) msg.obj;
6168 d.dismiss();
6169 break;
6170 }
6171 }
6172 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006173 }
6174
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 final class LocalService extends ActivityTaskManagerInternal {
6176 @Override
6177 public SleepToken acquireSleepToken(String tag, int displayId) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006178 Objects.requireNonNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006179 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006180 }
6181
6182 @Override
6183 public ComponentName getHomeActivityForUser(int userId) {
6184 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006185 final ActivityRecord homeActivity =
Louis Chang149d5c82019-12-30 09:47:39 +08006186 mRootWindowContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006187 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 }
6189 }
6190
6191 @Override
6192 public void onLocalVoiceInteractionStarted(IBinder activity,
6193 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6194 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006195 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006196 }
6197 }
6198
6199 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006200 public void notifySingleTaskDisplayDrawn(int displayId) {
6201 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6202 }
6203
6204 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 public void notifyAppTransitionFinished() {
6206 synchronized (mGlobalLock) {
6207 mStackSupervisor.notifyAppTransitionDone();
6208 }
6209 }
6210
6211 @Override
6212 public void notifyAppTransitionCancelled() {
6213 synchronized (mGlobalLock) {
6214 mStackSupervisor.notifyAppTransitionDone();
6215 }
6216 }
6217
6218 @Override
6219 public List<IBinder> getTopVisibleActivities() {
6220 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006221 return mRootWindowContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 }
6223 }
6224
6225 @Override
6226 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6227 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006228 mRootWindowContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 }
6230 }
6231
6232 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006233 public int startActivitiesAsPackage(String packageName, @Nullable String featureId,
6234 int userId, Intent[] intents, Bundle bOptions) {
Daulet Zhanguzinc6c641f2020-01-02 17:18:30 +00006235 Objects.requireNonNull(intents, "intents");
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006236 final String[] resolvedTypes = new String[intents.length];
6237
6238 // UID of the package on user userId.
6239 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6240 // packageUid may not be initialized.
6241 int packageUid = 0;
6242 final long ident = Binder.clearCallingIdentity();
6243
6244 try {
6245 for (int i = 0; i < intents.length; i++) {
6246 resolvedTypes[i] =
6247 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6248 }
6249
6250 packageUid = AppGlobals.getPackageManager().getPackageUid(
6251 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6252 } catch (RemoteException e) {
6253 // Shouldn't happen.
6254 } finally {
6255 Binder.restoreCallingIdentity(ident);
6256 }
6257
Riddle Hsu591bf612019-02-14 17:55:31 +08006258 return getActivityStartController().startActivitiesInPackage(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006259 packageUid, packageName, featureId,
Riddle Hsu591bf612019-02-14 17:55:31 +08006260 intents, resolvedTypes, null /* resultTo */,
6261 SafeActivityOptions.fromBundle(bOptions), userId,
6262 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6263 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006264 }
6265
6266 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006267 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006268 String callingPackage, @Nullable String callingFeatureId, Intent[] intents,
6269 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
6270 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006271 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006272 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006273 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006274 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006275 realCallingUid, callingPackage, callingFeatureId, intents, resolvedTypes,
6276 resultTo, options, userId, validateIncomingUser, originatingPendingIntent,
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006277 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006278 }
6279 }
6280
6281 @Override
6282 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006283 String callingPackage, @Nullable String callingFeatureId, Intent intent,
6284 String resolvedType, IBinder resultTo, String resultWho, int requestCode,
6285 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason,
6286 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006287 boolean allowBackgroundActivityStart) {
Andrii Kulianf9e5c9f2019-07-16 11:24:45 -07006288 assertPackageMatchesCallingUid(callingPackage);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006289 synchronized (mGlobalLock) {
6290 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006291 realCallingUid, callingPackage, callingFeatureId, intent, resolvedType,
6292 resultTo, resultWho, requestCode, startFlags, options, userId, inTask,
6293 reason, validateIncomingUser, originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006294 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006295 }
6296 }
6297
6298 @Override
Philip P. Moltmannee295092020-02-10 08:46:26 -08006299 public int startActivityAsUser(IApplicationThread caller, String callerPackage,
Alex Kershaw16406c32020-02-17 12:28:53 +00006300 @Nullable String callerFeatureId, Intent intent, @Nullable IBinder resultTo,
6301 int startFlags, Bundle options, int userId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006302 return ActivityTaskManagerService.this.startActivityAsUser(
Philip P. Moltmannee295092020-02-10 08:46:26 -08006303 caller, callerPackage, callerFeatureId, intent,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006304 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
Alex Kershaw16406c32020-02-17 12:28:53 +00006305 resultTo, null, 0, startFlags, null, options, userId,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006306 false /*validateIncomingUser*/);
6307 }
6308
6309 @Override
lumark588a3e82018-07-20 18:53:54 +08006310 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006311 synchronized (mGlobalLock) {
6312
6313 // We might change the visibilities here, so prepare an empty app transition which
6314 // might be overridden later if we actually change visibilities.
Louis Chang677921f2019-12-06 16:44:24 +08006315 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006316 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006317 if (displayContent == null) {
lumark52ea28e2018-11-09 17:30:47 +08006318 return;
6319 }
Louis Chang677921f2019-12-06 16:44:24 +08006320 final DisplayContent dc = displayContent.mDisplayContent;
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006321 final boolean wasTransitionSet =
6322 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006323 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006324 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006325 }
Louis Chang149d5c82019-12-30 09:47:39 +08006326 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006327
6328 // If there was a transition set already we don't want to interfere with it as we
6329 // might be starting it too early.
6330 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006331 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006332 }
6333 }
6334 if (callback != null) {
6335 callback.run();
6336 }
6337 }
6338
6339 @Override
6340 public void notifyKeyguardTrustedChanged() {
6341 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006342 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Louis Chang149d5c82019-12-30 09:47:39 +08006343 mRootWindowContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006344 }
6345 }
6346 }
6347
6348 /**
6349 * Called after virtual display Id is updated by
6350 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6351 * {@param vrVr2dDisplayId}.
6352 */
6353 @Override
6354 public void setVr2dDisplayId(int vr2dDisplayId) {
6355 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6356 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006357 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006358 }
6359 }
6360
6361 @Override
6362 public void setFocusedActivity(IBinder token) {
6363 synchronized (mGlobalLock) {
6364 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6365 if (r == null) {
6366 throw new IllegalArgumentException(
6367 "setFocusedActivity: No activity record matching token=" + token);
6368 }
Louis Chang19443452018-10-09 12:10:21 +08006369 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Louis Chang149d5c82019-12-30 09:47:39 +08006370 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006371 }
6372 }
6373 }
6374
6375 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006376 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006377 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006378 }
6379
6380 @Override
6381 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006382 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006383 }
6384
6385 @Override
6386 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006387 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006388 }
6389
6390 @Override
6391 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6392 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6393 }
6394
6395 @Override
6396 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006397 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006398 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006399
6400 @Override
6401 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6402 synchronized (mGlobalLock) {
6403 mActiveVoiceInteractionServiceComponent = component;
6404 }
6405 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006406
6407 @Override
6408 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6409 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6410 return;
6411 }
6412 synchronized (mGlobalLock) {
6413 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6414 if (types == null) {
6415 if (uid < 0) {
6416 return;
6417 }
6418 types = new ArrayMap<>();
6419 mAllowAppSwitchUids.put(userId, types);
6420 }
6421 if (uid < 0) {
6422 types.remove(type);
6423 } else {
6424 types.put(type, uid);
6425 }
6426 }
6427 }
6428
6429 @Override
6430 public void onUserStopped(int userId) {
6431 synchronized (mGlobalLock) {
6432 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6433 mAllowAppSwitchUids.remove(userId);
6434 }
6435 }
6436
6437 @Override
6438 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6439 synchronized (mGlobalLock) {
6440 return ActivityTaskManagerService.this.isGetTasksAllowed(
6441 caller, callingPid, callingUid);
6442 }
6443 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006444
Riddle Hsua0536432019-02-16 00:38:59 +08006445 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006446 @Override
6447 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006448 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006449 mProcessNames.put(proc.mName, proc.mUid, proc);
6450 }
6451 }
6452
Riddle Hsua0536432019-02-16 00:38:59 +08006453 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006454 @Override
6455 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006456 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006457 mProcessNames.remove(name, uid);
6458 }
6459 }
6460
Riddle Hsua0536432019-02-16 00:38:59 +08006461 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006462 @Override
6463 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006464 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006465 if (proc == mHomeProcess) {
6466 mHomeProcess = null;
6467 }
6468 if (proc == mPreviousProcess) {
6469 mPreviousProcess = null;
6470 }
6471 }
6472 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006473
Riddle Hsua0536432019-02-16 00:38:59 +08006474 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006475 @Override
6476 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006477 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006478 return mTopProcessState;
6479 }
6480 }
6481
Riddle Hsua0536432019-02-16 00:38:59 +08006482 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006483 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006484 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006485 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006486 return proc == mHeavyWeightProcess;
6487 }
6488 }
6489
Riddle Hsua0536432019-02-16 00:38:59 +08006490 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006491 @Override
6492 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006493 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006494 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6495 }
6496 }
6497
6498 @Override
6499 public void finishHeavyWeightApp() {
6500 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006501 if (mHeavyWeightProcess != null) {
6502 mHeavyWeightProcess.finishActivities();
6503 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006504 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6505 mHeavyWeightProcess);
6506 }
6507 }
6508
Riddle Hsua0536432019-02-16 00:38:59 +08006509 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006510 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006511 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006512 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006513 return isSleepingLocked();
6514 }
6515 }
6516
6517 @Override
6518 public boolean isShuttingDown() {
6519 synchronized (mGlobalLock) {
6520 return mShuttingDown;
6521 }
6522 }
6523
6524 @Override
6525 public boolean shuttingDown(boolean booted, int timeout) {
6526 synchronized (mGlobalLock) {
6527 mShuttingDown = true;
Louis Chang149d5c82019-12-30 09:47:39 +08006528 mRootWindowContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006529 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006530 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006531 return mStackSupervisor.shutdownLocked(timeout);
6532 }
6533 }
6534
6535 @Override
6536 public void enableScreenAfterBoot(boolean booted) {
6537 synchronized (mGlobalLock) {
Jeff Changd136e772019-11-05 20:33:52 +08006538 writeBootProgressEnableScreen(SystemClock.uptimeMillis());
Wale Ogunwalef6733932018-06-27 05:14:34 -07006539 mWindowManager.enableScreenAfterBoot();
6540 updateEventDispatchingLocked(booted);
6541 }
6542 }
6543
6544 @Override
6545 public boolean showStrictModeViolationDialog() {
6546 synchronized (mGlobalLock) {
6547 return mShowDialogs && !mSleeping && !mShuttingDown;
6548 }
6549 }
6550
6551 @Override
6552 public void showSystemReadyErrorDialogsIfNeeded() {
6553 synchronized (mGlobalLock) {
6554 try {
6555 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6556 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6557 + " data partition or your device will be unstable.");
6558 mUiHandler.post(() -> {
6559 if (mShowDialogs) {
6560 AlertDialog d = new BaseErrorDialog(mUiContext);
6561 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6562 d.setCancelable(false);
6563 d.setTitle(mUiContext.getText(R.string.android_system_label));
6564 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6565 d.setButton(DialogInterface.BUTTON_POSITIVE,
6566 mUiContext.getText(R.string.ok),
6567 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6568 d.show();
6569 }
6570 });
6571 }
6572 } catch (RemoteException e) {
6573 }
6574
6575 if (!Build.isBuildConsistent()) {
6576 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6577 mUiHandler.post(() -> {
6578 if (mShowDialogs) {
6579 AlertDialog d = new BaseErrorDialog(mUiContext);
6580 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6581 d.setCancelable(false);
6582 d.setTitle(mUiContext.getText(R.string.android_system_label));
6583 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6584 d.setButton(DialogInterface.BUTTON_POSITIVE,
6585 mUiContext.getText(R.string.ok),
6586 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6587 d.show();
6588 }
6589 });
6590 }
6591 }
6592 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006593
6594 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006595 public void onProcessMapped(int pid, WindowProcessController proc) {
6596 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006597 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006598 }
6599 }
6600
6601 @Override
6602 public void onProcessUnMapped(int pid) {
6603 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006604 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006605 }
6606 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006607
6608 @Override
6609 public void onPackageDataCleared(String name) {
6610 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006611 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006612 mAppWarnings.onPackageDataCleared(name);
6613 }
6614 }
6615
6616 @Override
6617 public void onPackageUninstalled(String name) {
6618 synchronized (mGlobalLock) {
6619 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006620 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006621 }
6622 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006623
6624 @Override
6625 public void onPackageAdded(String name, boolean replacing) {
6626 synchronized (mGlobalLock) {
6627 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6628 }
6629 }
6630
6631 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006632 public void onPackageReplaced(ApplicationInfo aInfo) {
6633 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006634 mRootWindowContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006635 }
6636 }
6637
6638 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006639 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6640 synchronized (mGlobalLock) {
6641 return compatibilityInfoForPackageLocked(ai);
6642 }
6643 }
6644
Yunfan Chen75157d72018-07-27 14:47:21 +09006645 /**
6646 * Set the corresponding display information for the process global configuration. To be
6647 * called when we need to show IME on a different display.
6648 *
6649 * @param pid The process id associated with the IME window.
6650 * @param displayId The ID of the display showing the IME.
6651 */
6652 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006653 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006654 // Don't update process-level configuration for Multi-Client IME process since other
6655 // IMEs on other displays will also receive this configuration change due to IME
6656 // services use the same application config/context.
6657 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006658
Yunfan Chen75157d72018-07-27 14:47:21 +09006659 if (pid == MY_PID || pid < 0) {
6660 if (DEBUG_CONFIGURATION) {
6661 Slog.w(TAG,
6662 "Trying to update display configuration for system/invalid process.");
6663 }
6664 return;
6665 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006666 synchronized (mGlobalLock) {
Louis Chang677921f2019-12-06 16:44:24 +08006667 final DisplayContent displayContent =
Louis Chang149d5c82019-12-30 09:47:39 +08006668 mRootWindowContainer.getDisplayContent(displayId);
Louis Chang677921f2019-12-06 16:44:24 +08006669 if (displayContent == null) {
Yunfan Chencafc7062019-01-22 17:21:32 +09006670 // Call might come when display is not yet added or has been removed.
6671 if (DEBUG_CONFIGURATION) {
6672 Slog.w(TAG, "Trying to update display configuration for non-existing "
6673 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006674 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006675 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006676 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006677 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006678 if (process == null) {
6679 if (DEBUG_CONFIGURATION) {
6680 Slog.w(TAG, "Trying to update display configuration for invalid "
6681 + "process, pid=" + pid);
6682 }
6683 return;
6684 }
lumarkddc77fb2019-06-27 22:22:23 +08006685 process.mIsImeProcess = true;
Andrii Kulianfa23a9e2019-10-10 15:15:36 -07006686 process.registerDisplayConfigurationListener(displayContent);
Yunfan Chencafc7062019-01-22 17:21:32 +09006687 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006688 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006689
6690 @Override
6691 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006692 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006693 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006694 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08006695 if (r != null && r.getRootTask() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006696 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006697 }
6698 }
6699 }
6700
6701 @Override
6702 public void clearPendingResultForActivity(IBinder activityToken,
6703 WeakReference<PendingIntentRecord> pir) {
6704 synchronized (mGlobalLock) {
6705 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6706 if (r != null && r.pendingResults != null) {
6707 r.pendingResults.remove(pir);
6708 }
6709 }
6710 }
6711
6712 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006713 public ActivityTokens getTopActivityForTask(int taskId) {
6714 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006715 final Task task = mRootWindowContainer.anyTaskForId(taskId);
Louis Changcdec0802019-11-11 11:45:07 +08006716 if (task == null) {
Sunny Goyald40c3452019-03-20 12:46:55 -07006717 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6718 + " Requested task not found");
6719 return null;
6720 }
Wale Ogunwale21e06482019-11-18 05:14:15 -08006721 final ActivityRecord activity = task.getTopNonFinishingActivity();
Sunny Goyald40c3452019-03-20 12:46:55 -07006722 if (activity == null) {
6723 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6724 + " Requested activity not found");
6725 return null;
6726 }
6727 if (!activity.attachedToProcess()) {
6728 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6729 + activity);
6730 return null;
6731 }
6732 return new ActivityTokens(activity.appToken, activity.assistToken,
6733 activity.app.getThread());
6734 }
6735 }
6736
6737 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006738 public IIntentSender getIntentSender(int type, String packageName,
Philip P. Moltmannee295092020-02-10 08:46:26 -08006739 @Nullable String featureId, int callingUid, int userId, IBinder token,
6740 String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes,
6741 int flags, Bundle bOptions) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006742 synchronized (mGlobalLock) {
Philip P. Moltmannee295092020-02-10 08:46:26 -08006743 return getIntentSenderLocked(type, packageName, featureId, callingUid, userId,
6744 token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006745 }
6746 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006747
6748 @Override
6749 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6750 synchronized (mGlobalLock) {
6751 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6752 if (r == null) {
6753 return null;
6754 }
6755 if (r.mServiceConnectionsHolder == null) {
6756 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6757 ActivityTaskManagerService.this, r);
6758 }
6759
6760 return r.mServiceConnectionsHolder;
6761 }
6762 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006763
6764 @Override
6765 public Intent getHomeIntent() {
6766 synchronized (mGlobalLock) {
6767 return ActivityTaskManagerService.this.getHomeIntent();
6768 }
6769 }
6770
6771 @Override
6772 public boolean startHomeActivity(int userId, String reason) {
6773 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006774 return mRootWindowContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006775 }
6776 }
6777
6778 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006779 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006780 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006781 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006782 return mRootWindowContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006783 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006784 }
Chilun8b1f1be2019-03-13 17:14:36 +08006785 }
6786
6787 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006788 public boolean startHomeOnAllDisplays(int userId, String reason) {
6789 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006790 return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006791 }
6792 }
6793
Riddle Hsua0536432019-02-16 00:38:59 +08006794 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006795 @Override
6796 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006797 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006798 if (mFactoryTest == FACTORY_TEST_OFF) {
6799 return false;
6800 }
6801 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6802 && wpc.mName.equals(mTopComponent.getPackageName())) {
6803 return true;
6804 }
6805 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6806 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6807 }
6808 }
6809
6810 @Override
6811 public void updateTopComponentForFactoryTest() {
6812 synchronized (mGlobalLock) {
6813 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6814 return;
6815 }
6816 final ResolveInfo ri = mContext.getPackageManager()
6817 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6818 final CharSequence errorMsg;
6819 if (ri != null) {
6820 final ActivityInfo ai = ri.activityInfo;
6821 final ApplicationInfo app = ai.applicationInfo;
6822 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6823 mTopAction = Intent.ACTION_FACTORY_TEST;
6824 mTopData = null;
6825 mTopComponent = new ComponentName(app.packageName, ai.name);
6826 errorMsg = null;
6827 } else {
6828 errorMsg = mContext.getResources().getText(
6829 com.android.internal.R.string.factorytest_not_system);
6830 }
6831 } else {
6832 errorMsg = mContext.getResources().getText(
6833 com.android.internal.R.string.factorytest_no_action);
6834 }
6835 if (errorMsg == null) {
6836 return;
6837 }
6838
6839 mTopAction = null;
6840 mTopData = null;
6841 mTopComponent = null;
6842 mUiHandler.post(() -> {
6843 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6844 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006845 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006846 });
6847 }
6848 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849
Riddle Hsua0536432019-02-16 00:38:59 +08006850 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 @Override
6852 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6853 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006854 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006855 // Remove this application's activities from active lists.
Louis Chang149d5c82019-12-30 09:47:39 +08006856 boolean hasVisibleActivities = mRootWindowContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006857
6858 wpc.clearRecentTasks();
6859 wpc.clearActivities();
6860
6861 if (wpc.isInstrumenting()) {
6862 finishInstrumentationCallback.run();
6863 }
6864
Jorim Jaggid0752812018-10-16 16:07:20 +02006865 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006866 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006867 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006868 if (!mRootWindowContainer.resumeFocusedStacksTopActivities()) {
Jorim Jaggid0752812018-10-16 16:07:20 +02006869 // If there was nothing to resume, and we are not already restarting
6870 // this process, but there is a visible activity that is hosted by the
6871 // process...then make sure all visible activities are running, taking
6872 // care of restarting this process.
Louis Chang149d5c82019-12-30 09:47:39 +08006873 mRootWindowContainer.ensureActivitiesVisible(null, 0,
Jorim Jaggid0752812018-10-16 16:07:20 +02006874 !PRESERVE_WINDOWS);
6875 }
6876 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006877 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006878 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 }
6880 }
6881 }
6882
6883 @Override
6884 public void closeSystemDialogs(String reason) {
6885 enforceNotIsolatedCaller("closeSystemDialogs");
6886
6887 final int pid = Binder.getCallingPid();
6888 final int uid = Binder.getCallingUid();
6889 final long origId = Binder.clearCallingIdentity();
6890 try {
6891 synchronized (mGlobalLock) {
6892 // Only allow this from foreground processes, so that background
6893 // applications can't abuse it to prevent system UI from being shown.
6894 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006895 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006896 if (!proc.isPerceptible()) {
6897 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6898 + " from background process " + proc);
6899 return;
6900 }
6901 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006902 mWindowManager.closeSystemDialogs(reason);
6903
Louis Chang149d5c82019-12-30 09:47:39 +08006904 mRootWindowContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006905 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006906 // Call into AM outside the synchronized block.
6907 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006908 } finally {
6909 Binder.restoreCallingIdentity(origId);
6910 }
6911 }
6912
6913 @Override
6914 public void cleanupDisabledPackageComponents(
6915 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6916 synchronized (mGlobalLock) {
6917 // Clean-up disabled activities.
Louis Chang149d5c82019-12-30 09:47:39 +08006918 if (mRootWindowContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006919 packageName, disabledClasses, true, false, userId) && booted) {
Louis Chang149d5c82019-12-30 09:47:39 +08006920 mRootWindowContainer.resumeFocusedStacksTopActivities();
Riddle Hsufc8ab262019-12-31 15:31:24 +08006921 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006922 }
6923
6924 // Clean-up disabled tasks
6925 getRecentTasks().cleanupDisabledPackageTasksLocked(
6926 packageName, disabledClasses, userId);
6927 }
6928 }
6929
6930 @Override
6931 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6932 int userId) {
6933 synchronized (mGlobalLock) {
6934
6935 boolean didSomething =
6936 getActivityStartController().clearPendingActivityLaunches(packageName);
Louis Chang149d5c82019-12-30 09:47:39 +08006937 didSomething |= mRootWindowContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006938 null, doit, evenPersistent, userId);
6939 return didSomething;
6940 }
6941 }
6942
6943 @Override
6944 public void resumeTopActivities(boolean scheduleIdle) {
6945 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08006946 mRootWindowContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 if (scheduleIdle) {
Riddle Hsufc8ab262019-12-31 15:31:24 +08006948 mStackSupervisor.scheduleIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006949 }
6950 }
6951 }
6952
Riddle Hsua0536432019-02-16 00:38:59 +08006953 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 @Override
6955 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006956 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006957 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6958 }
6959 }
6960
Riddle Hsua0536432019-02-16 00:38:59 +08006961 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006962 @Override
6963 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006964 synchronized (mGlobalLockWithoutBoost) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006965 if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
6966 Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "attachApplication:" + wpc.mName);
6967 }
6968 try {
Louis Chang149d5c82019-12-30 09:47:39 +08006969 return mRootWindowContainer.attachApplication(wpc);
Riddle Hsu2ca561b2019-10-08 21:58:58 +08006970 } finally {
6971 Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
6972 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006973 }
6974 }
6975
6976 @Override
6977 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6978 try {
6979 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6980 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6981 }
6982 } catch (RemoteException ex) {
6983 throw new SecurityException("Fail to check is caller a privileged app", ex);
6984 }
6985
6986 synchronized (mGlobalLock) {
6987 final long ident = Binder.clearCallingIdentity();
6988 try {
6989 if (mAmInternal.shouldConfirmCredentials(userId)) {
6990 if (mKeyguardController.isKeyguardLocked()) {
6991 // Showing launcher to avoid user entering credential twice.
6992 startHomeActivity(currentUserId, "notifyLockedProfile");
6993 }
Louis Chang149d5c82019-12-30 09:47:39 +08006994 mRootWindowContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 }
6996 } finally {
6997 Binder.restoreCallingIdentity(ident);
6998 }
6999 }
7000 }
7001
7002 @Override
7003 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7004 mAmInternal.enforceCallingPermission(
7005 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
7006
7007 synchronized (mGlobalLock) {
7008 final long ident = Binder.clearCallingIdentity();
7009 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01007010 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7011 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07007012 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007013 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
7014 UserHandle.CURRENT);
7015 } finally {
7016 Binder.restoreCallingIdentity(ident);
7017 }
7018 }
7019 }
7020
7021 @Override
7022 public void writeActivitiesToProto(ProtoOutputStream proto) {
7023 synchronized (mGlobalLock) {
7024 // The output proto of "activity --proto activities"
Wale Ogunwalef342f062020-01-27 07:34:13 -08007025 mRootWindowContainer.dumpDebug(
7026 proto, ROOT_WINDOW_CONTAINER, WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007027 }
7028 }
7029
7030 @Override
7031 public void saveANRState(String reason) {
7032 synchronized (mGlobalLock) {
7033 final StringWriter sw = new StringWriter();
7034 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7035 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
7036 if (reason != null) {
7037 pw.println(" Reason: " + reason);
7038 }
7039 pw.println();
7040 getActivityStartController().dump(pw, " ", null);
7041 pw.println();
7042 pw.println("-------------------------------------------------------------------------------");
7043 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
7044 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
7045 "" /* header */);
7046 pw.println();
7047 pw.close();
7048
7049 mLastANRState = sw.toString();
7050 }
7051 }
7052
7053 @Override
7054 public void clearSavedANRState() {
7055 synchronized (mGlobalLock) {
7056 mLastANRState = null;
7057 }
7058 }
7059
7060 @Override
7061 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
7062 boolean dumpAll, boolean dumpClient, String dumpPackage) {
7063 synchronized (mGlobalLock) {
7064 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7065 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7066 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7067 dumpLastANRLocked(pw);
7068 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7069 dumpLastANRTracesLocked(pw);
7070 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7071 dumpActivityStarterLocked(pw, dumpPackage);
7072 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7073 dumpActivityContainersLocked(pw);
7074 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7075 if (getRecentTasks() != null) {
7076 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7077 }
7078 }
7079 }
7080 }
7081
7082 @Override
7083 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7084 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7085 int wakefulness) {
7086 synchronized (mGlobalLock) {
7087 if (mHomeProcess != null && (dumpPackage == null
7088 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7089 if (needSep) {
7090 pw.println();
7091 needSep = false;
7092 }
7093 pw.println(" mHomeProcess: " + mHomeProcess);
7094 }
7095 if (mPreviousProcess != null && (dumpPackage == null
7096 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7097 if (needSep) {
7098 pw.println();
7099 needSep = false;
7100 }
7101 pw.println(" mPreviousProcess: " + mPreviousProcess);
7102 }
7103 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7104 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7105 StringBuilder sb = new StringBuilder(128);
7106 sb.append(" mPreviousProcessVisibleTime: ");
7107 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7108 pw.println(sb);
7109 }
7110 if (mHeavyWeightProcess != null && (dumpPackage == null
7111 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7112 if (needSep) {
7113 pw.println();
7114 needSep = false;
7115 }
7116 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7117 }
7118 if (dumpPackage == null) {
7119 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Louis Chang149d5c82019-12-30 09:47:39 +08007120 mRootWindowContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007121 }
7122 if (dumpAll) {
7123 if (dumpPackage == null) {
7124 pw.println(" mConfigWillChange: "
7125 + getTopDisplayFocusedStack().mConfigWillChange);
7126 }
7127 if (mCompatModePackages.getPackages().size() > 0) {
7128 boolean printed = false;
7129 for (Map.Entry<String, Integer> entry
7130 : mCompatModePackages.getPackages().entrySet()) {
7131 String pkg = entry.getKey();
7132 int mode = entry.getValue();
7133 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7134 continue;
7135 }
7136 if (!printed) {
7137 pw.println(" mScreenCompatPackages:");
7138 printed = true;
7139 }
7140 pw.println(" " + pkg + ": " + mode);
7141 }
7142 }
7143 }
7144
7145 if (dumpPackage == null) {
7146 pw.println(" mWakefulness="
7147 + PowerManagerInternal.wakefulnessToString(wakefulness));
Louis Chang149d5c82019-12-30 09:47:39 +08007148 pw.println(" mSleepTokens=" + mRootWindowContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007149 if (mRunningVoice != null) {
7150 pw.println(" mRunningVoice=" + mRunningVoice);
7151 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7152 }
7153 pw.println(" mSleeping=" + mSleeping);
7154 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7155 pw.println(" mVrController=" + mVrController);
7156 }
7157 if (mCurAppTimeTracker != null) {
7158 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7159 }
7160 if (mAllowAppSwitchUids.size() > 0) {
7161 boolean printed = false;
7162 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7163 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7164 for (int j = 0; j < types.size(); j++) {
7165 if (dumpPackage == null ||
7166 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7167 if (needSep) {
7168 pw.println();
7169 needSep = false;
7170 }
7171 if (!printed) {
7172 pw.println(" mAllowAppSwitchUids:");
7173 printed = true;
7174 }
7175 pw.print(" User ");
7176 pw.print(mAllowAppSwitchUids.keyAt(i));
7177 pw.print(": Type ");
7178 pw.print(types.keyAt(j));
7179 pw.print(" = ");
7180 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7181 pw.println();
7182 }
7183 }
7184 }
7185 }
7186 if (dumpPackage == null) {
7187 if (mController != null) {
7188 pw.println(" mController=" + mController
7189 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7190 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007191 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7192 pw.println(" mLaunchingActivityWakeLock="
7193 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007194 }
7195
7196 return needSep;
7197 }
7198 }
7199
7200 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007201 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7202 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007203 synchronized (mGlobalLock) {
7204 if (dumpPackage == null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007205 getGlobalConfiguration().dumpDebug(proto, GLOBAL_CONFIGURATION);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007206 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007207 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7208 if (mRunningVoice != null) {
7209 final long vrToken = proto.start(
7210 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7211 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7212 mRunningVoice.toString());
Jeffrey Huangcb782852019-12-05 11:28:11 -08007213 mVoiceWakeLock.dumpDebug(
sanryhuang498e77e2018-12-06 14:57:01 +08007214 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7215 proto.end(vrToken);
7216 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007217 mVrController.dumpDebug(proto,
sanryhuang498e77e2018-12-06 14:57:01 +08007218 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007219 if (mController != null) {
7220 final long token = proto.start(CONTROLLER);
Wally Yau0eb29f62020-01-08 10:16:43 -08007221 proto.write(ActivityManagerServiceDumpProcessesProto.Controller.CONTROLLER,
7222 mController.toString());
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7224 proto.end(token);
7225 }
Jeffrey Huangcb782852019-12-05 11:28:11 -08007226 mStackSupervisor.mGoingToSleepWakeLock.dumpDebug(proto, GOING_TO_SLEEP);
7227 mStackSupervisor.mLaunchingActivityWakeLock.dumpDebug(proto,
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007228 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 }
7230
7231 if (mHomeProcess != null && (dumpPackage == null
7232 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007233 mHomeProcess.dumpDebug(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007234 }
7235
7236 if (mPreviousProcess != null && (dumpPackage == null
7237 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007238 mPreviousProcess.dumpDebug(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007239 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7240 }
7241
7242 if (mHeavyWeightProcess != null && (dumpPackage == null
7243 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007244 mHeavyWeightProcess.dumpDebug(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007245 }
7246
7247 for (Map.Entry<String, Integer> entry
7248 : mCompatModePackages.getPackages().entrySet()) {
7249 String pkg = entry.getKey();
7250 int mode = entry.getValue();
7251 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7252 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7253 proto.write(PACKAGE, pkg);
7254 proto.write(MODE, mode);
7255 proto.end(compatToken);
7256 }
7257 }
7258
7259 if (mCurAppTimeTracker != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08007260 mCurAppTimeTracker.dumpDebug(proto, CURRENT_TRACKER, true);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007261 }
7262
7263 }
7264 }
7265
7266 @Override
7267 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7268 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7269 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007270 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7271 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007272 }
7273
7274 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007275 public void dumpForOom(PrintWriter pw) {
7276 synchronized (mGlobalLock) {
7277 pw.println(" mHomeProcess: " + mHomeProcess);
7278 pw.println(" mPreviousProcess: " + mPreviousProcess);
7279 if (mHeavyWeightProcess != null) {
7280 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7281 }
7282 }
7283 }
7284
7285 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007286 public boolean canGcNow() {
7287 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007288 return isSleeping() || mRootWindowContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007289 }
7290 }
7291
Riddle Hsua0536432019-02-16 00:38:59 +08007292 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007293 @Override
7294 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007295 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007296 if (mRootWindowContainer == null) {
7297 // Return null if mRootWindowContainer not yet initialize, while update
Louis Chang3ff72a82019-12-17 12:12:59 +08007298 // oomadj after AMS created.
7299 return null;
7300 }
Louis Chang149d5c82019-12-30 09:47:39 +08007301 final ActivityRecord top = mRootWindowContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007302 return top != null ? top.app : null;
7303 }
7304 }
7305
Riddle Hsua0536432019-02-16 00:38:59 +08007306 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007307 @Override
7308 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007309 synchronized (mGlobalLockWithoutBoost) {
Louis Chang149d5c82019-12-30 09:47:39 +08007310 if (mRootWindowContainer != null) {
7311 mRootWindowContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007312 }
7313 }
7314 }
7315
7316 @Override
7317 public void scheduleDestroyAllActivities(String reason) {
7318 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007319 mRootWindowContainer.scheduleDestroyAllActivities(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007320 }
7321 }
7322
7323 @Override
7324 public void removeUser(int userId) {
7325 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007326 mRootWindowContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007327 }
7328 }
7329
7330 @Override
7331 public boolean switchUser(int userId, UserState userState) {
7332 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007333 return mRootWindowContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007334 }
7335 }
7336
7337 @Override
7338 public void onHandleAppCrash(WindowProcessController wpc) {
7339 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007340 mRootWindowContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007341 }
7342 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007343
7344 @Override
7345 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7346 synchronized (mGlobalLock) {
Louis Chang149d5c82019-12-30 09:47:39 +08007347 return mRootWindowContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007348 }
7349 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007350
Riddle Hsua0536432019-02-16 00:38:59 +08007351 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007352 @Override
7353 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007354 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007355 }
7356
Riddle Hsua0536432019-02-16 00:38:59 +08007357 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007358 @Override
7359 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007360 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007361 }
7362
Riddle Hsua0536432019-02-16 00:38:59 +08007363 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007364 @Override
7365 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007366 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007367 }
7368
Riddle Hsua0536432019-02-16 00:38:59 +08007369 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007370 @Override
7371 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007372 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007373 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007374
7375 @Override
7376 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007377 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007378 mPendingTempWhitelist.put(uid, tag);
7379 }
7380 }
7381
7382 @Override
7383 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007384 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007385 mPendingTempWhitelist.remove(uid);
7386 }
7387 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007388
7389 @Override
7390 public boolean handleAppCrashInActivityController(String processName, int pid,
7391 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7392 Runnable killCrashingAppCallback) {
7393 synchronized (mGlobalLock) {
7394 if (mController == null) {
7395 return false;
7396 }
7397
7398 try {
7399 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7400 stackTrace)) {
7401 killCrashingAppCallback.run();
7402 return true;
7403 }
7404 } catch (RemoteException e) {
7405 mController = null;
7406 Watchdog.getInstance().setActivityController(null);
7407 }
7408 return false;
7409 }
7410 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007411
7412 @Override
7413 public void removeRecentTasksByPackageName(String packageName, int userId) {
7414 synchronized (mGlobalLock) {
7415 mRecentTasks.removeTasksByPackageName(packageName, userId);
7416 }
7417 }
7418
7419 @Override
7420 public void cleanupRecentTasksForUser(int userId) {
7421 synchronized (mGlobalLock) {
7422 mRecentTasks.cleanupLocked(userId);
7423 }
7424 }
7425
7426 @Override
7427 public void loadRecentTasksForUser(int userId) {
7428 synchronized (mGlobalLock) {
7429 mRecentTasks.loadUserRecentsLocked(userId);
7430 }
7431 }
7432
7433 @Override
7434 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7435 synchronized (mGlobalLock) {
7436 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7437 }
7438 }
7439
7440 @Override
7441 public void flushRecentTasks() {
7442 mRecentTasks.flush();
7443 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007444
7445 @Override
7446 public WindowProcessController getHomeProcess() {
7447 synchronized (mGlobalLock) {
7448 return mHomeProcess;
7449 }
7450 }
7451
7452 @Override
7453 public WindowProcessController getPreviousProcess() {
7454 synchronized (mGlobalLock) {
7455 return mPreviousProcess;
7456 }
7457 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007458
7459 @Override
7460 public void clearLockedTasks(String reason) {
7461 synchronized (mGlobalLock) {
7462 getLockTaskController().clearLockedTasks(reason);
7463 }
7464 }
7465
7466 @Override
7467 public void updateUserConfiguration() {
7468 synchronized (mGlobalLock) {
7469 final Configuration configuration = new Configuration(getGlobalConfiguration());
7470 final int currentUserId = mAmInternal.getCurrentUserId();
7471 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7472 configuration, currentUserId, Settings.System.canWrite(mContext));
7473 updateConfigurationLocked(configuration, null /* starting */,
7474 false /* initLocale */, false /* persistent */, currentUserId,
7475 false /* deferResume */);
7476 }
7477 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007478
7479 @Override
7480 public boolean canShowErrorDialogs() {
7481 synchronized (mGlobalLock) {
7482 return mShowDialogs && !mSleeping && !mShuttingDown
7483 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7484 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7485 mAmInternal.getCurrentUserId())
7486 && !(UserManager.isDeviceInDemoMode(mContext)
7487 && mAmInternal.getCurrentUser().isDemo());
7488 }
7489 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007490
7491 @Override
7492 public void setProfileApp(String profileApp) {
7493 synchronized (mGlobalLock) {
7494 mProfileApp = profileApp;
7495 }
7496 }
7497
7498 @Override
7499 public void setProfileProc(WindowProcessController wpc) {
7500 synchronized (mGlobalLock) {
7501 mProfileProc = wpc;
7502 }
7503 }
7504
7505 @Override
7506 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7507 synchronized (mGlobalLock) {
7508 mProfilerInfo = profilerInfo;
7509 }
7510 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007511
7512 @Override
7513 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7514 synchronized (mGlobalLock) {
7515 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7516 }
7517 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007518
7519 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007520 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
Peter Kalauskas4dc04602020-02-12 18:49:03 -08007521 boolean isLowResolution) {
7522 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, isLowResolution,
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007523 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007524 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007525
7526 @Override
7527 public boolean isUidForeground(int uid) {
7528 synchronized (mGlobalLock) {
7529 return ActivityTaskManagerService.this.isUidForeground(uid);
7530 }
7531 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007532
7533 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007534 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007535 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007536 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007537 }
7538 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007539
7540 @Override
7541 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007542 // Translate package names into UIDs
7543 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007544 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007545 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7546 if (uid >= 0) {
7547 result.add(uid);
7548 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007549 }
7550 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007551 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007552 }
7553 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007554 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007555}