blob: 7ce3e794b8aa1da107744366119e38ae970d1669 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwale214f3482018-10-04 11:00:47 -070050import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070053import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070054import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070055import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070056import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
57import 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 Ogunwale31913b52018-10-13 08:29:31 -070071import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
72import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
73import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080081import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070082import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070085import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
86import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Riddle Hsua0022cd2019-09-09 21:12:41 +0800125import android.annotation.IntDef;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100137import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400144import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700145import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.Notification;
147import android.app.NotificationManager;
148import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700149import android.app.PictureInPictureParams;
150import android.app.ProfilerInfo;
151import android.app.RemoteAction;
152import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700153import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.admin.DevicePolicyCache;
155import android.app.assist.AssistContent;
156import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700157import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700158import android.content.ActivityNotFoundException;
159import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700160import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700161import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700162import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.IIntentSender;
164import android.content.Intent;
165import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700166import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900167import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.ParceledListSlice;
172import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700173import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700175import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700176import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700177import android.graphics.Bitmap;
178import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700179import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700180import android.metrics.LogMaker;
181import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700182import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700183import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700184import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700185import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700186import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700187import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700188import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700189import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700190import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800191import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700195import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100196import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900212import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.telecom.TelecomManager;
214import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100215import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700216import android.util.ArrayMap;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700217import android.util.ArraySet;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.EventLog;
219import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700220import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700222import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700224import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700225import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700226import android.view.IRecentsAnimationRunner;
227import android.view.RemoteAnimationAdapter;
228import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700229import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700266import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800268import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100315 // How long we permit background activity starts after an activity in the process
316 // started or finished.
317 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318
Wale Ogunwale98875612018-10-12 07:53:02 -0700319 /** Used to indicate that an app transition should be animated. */
320 static final boolean ANIMATE = true;
321
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700322 /** Hardware-reported OpenGLES version. */
323 final int GL_ES_VERSION;
324
Wale Ogunwale31913b52018-10-13 08:29:31 -0700325 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
326 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
327 public static final String DUMP_LASTANR_CMD = "lastanr" ;
328 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
329 public static final String DUMP_STARTER_CMD = "starter" ;
330 public static final String DUMP_CONTAINERS_CMD = "containers" ;
331 public static final String DUMP_RECENTS_CMD = "recents" ;
332 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
333
Wale Ogunwale64258362018-10-16 15:13:37 -0700334 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
335 public static final int RELAUNCH_REASON_NONE = 0;
336 /** This activity is being relaunched due to windowing mode change. */
337 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
338 /** This activity is being relaunched due to a free-resize operation. */
339 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
340
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700341 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700342
Wale Ogunwalef6733932018-06-27 05:14:34 -0700343 /**
344 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
345 * change at runtime. Use mContext for non-UI purposes.
346 */
347 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700349 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700352 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700353 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800354 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800355 @VisibleForTesting
356 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 PowerManagerInternal mPowerManagerInternal;
358 private UsageStatsManagerInternal mUsageStatsInternal;
359
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700360 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 IntentFirewall mIntentFirewall;
362
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700363 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800364 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700366 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
368 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
369 *
370 * @see WindowManagerThreadPriorityBooster
371 */
372 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700373 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800374 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700375 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700376 private UserManagerService mUserManager;
377 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700378 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800379 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700380 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** All processes currently running that might have a window organized by name. */
382 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100383 /** All processes we currently have running mapped by pid and uid */
384 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** This is the process holding what we currently consider to be the "home" activity. */
386 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700387 /** The currently running heavy-weight process, if any. */
388 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700389 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /**
391 * This is the process holding the activity the user last visited that is in a different process
392 * from the one they are currently in.
393 */
394 WindowProcessController mPreviousProcess;
395 /** The time at which the previous process was last visible. */
396 long mPreviousProcessVisibleTime;
397
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700398 /** List of intents that were used to start the most recent tasks. */
399 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700400 /** State of external calls telling us if the device is awake or asleep. */
401 private boolean mKeyguardShown = false;
402
403 // Wrapper around VoiceInteractionServiceManager
404 private AssistUtils mAssistUtils;
405
406 // VoiceInteraction session ID that changes for each new request except when
407 // being called for multi-window assist in a single session.
408 private int mViSessionId = 1000;
409
410 // How long to wait in getAssistContextExtras for the activity and foreground services
411 // to respond with the result.
412 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
413
414 // How long top wait when going through the modern assist (which doesn't need to block
415 // on getting this result before starting to launch its UI).
416 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
417
418 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
419 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
420
Alison Cichowlas3e340502018-08-07 17:15:01 -0400421 // Permission tokens are used to temporarily granted a trusted app the ability to call
422 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
423 // showing any appropriate error messages to the user.
424 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
425 10 * MINUTE_IN_MILLIS;
426
427 // How long before the service actually expires a token. This is slightly longer than
428 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
429 // expiration exception.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
431 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
432
433 // How long the service will remember expired tokens, for the purpose of providing error
434 // messaging when a client uses an expired token.
435 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
436 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
437
438 // Activity tokens of system activities that are delegating their call to
439 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
440 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
441
442 // Permission tokens that have expired, but we remember for error reporting.
443 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
444
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700445 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
446
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447 // Keeps track of the active voice interaction service component, notified from
448 // VoiceInteractionManagerService
449 ComponentName mActiveVoiceInteractionServiceComponent;
450
Michal Karpinskida34cd42019-04-02 19:46:52 +0100451 // A map userId and all its companion app uids
452 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000453
Wale Ogunwalee2172292018-10-25 10:11:10 -0700454 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 KeyguardController mKeyguardController;
456 private final ClientLifecycleManager mLifecycleManager;
457 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700458 /** The controller for all operations related to locktask. */
459 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700460 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700462 boolean mSuppressResizeConfigChanges;
463
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700464 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 new UpdateConfigurationResult();
466
467 static final class UpdateConfigurationResult {
468 // Configuration changes that were updated.
469 int changes;
470 // If the activity was relaunched to match the new configuration.
471 boolean activityRelaunched;
472
473 void reset() {
474 changes = 0;
475 activityRelaunched = false;
476 }
477 }
478
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700479 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 private int mConfigurationSeq;
481 // To cache the list of supported system locales
482 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483
484 /**
485 * Temp object used when global and/or display override configuration is updated. It is also
486 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
487 * anyone...
488 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 private Configuration mTempConfig = new Configuration();
490
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 /** Temporary to avoid allocations. */
492 final StringBuilder mStringBuilder = new StringBuilder(256);
493
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 // Amount of time after a call to stopAppSwitches() during which we will
495 // prevent further untrusted switches from happening.
496 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
497
498 /**
499 * The time at which we will allow normal application switches again,
500 * after a call to {@link #stopAppSwitches()}.
501 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700502 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503 /**
504 * This is set to true after the first switch after mAppSwitchesAllowedTime
505 * is set; any switches after that will clear the time.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508
Ricky Wai906af482019-06-03 17:25:28 +0100509 /**
510 * Last stop app switches time, apps finished before this time cannot start background activity
511 * even if they are in grace period.
512 */
513 private long mLastStopAppSwitchesTime;
514
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 IActivityController mController = null;
516 boolean mControllerIsAMonkey = false;
517
Wale Ogunwale214f3482018-10-04 11:00:47 -0700518 final int mFactoryTest;
519
520 /** Used to control how we initialize the service. */
521 ComponentName mTopComponent;
522 String mTopAction = Intent.ACTION_MAIN;
523 String mTopData;
524
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800525 /** Profiling app information. */
526 String mProfileApp = null;
527 WindowProcessController mProfileProc = null;
528 ProfilerInfo mProfilerInfo = null;
529
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700531 * Dump of the activity state at the time of the last ANR. Cleared after
532 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
533 */
534 String mLastANRState;
535
536 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700537 * Used to retain an update lock when the foreground activity is in
538 * immersive mode.
539 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700540 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541
542 /**
543 * Packages that are being allowed to perform unrestricted app switches. Mapping is
544 * User -> Type -> uid.
545 */
546 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
547
548 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 private int mThumbnailWidth;
550 private int mThumbnailHeight;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700551
552 /**
553 * Flag that indicates if multi-window is enabled.
554 *
555 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
556 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
557 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
558 * At least one of the forms of multi-window must be enabled in order for this flag to be
559 * initialized to 'true'.
560 *
561 * @see #mSupportsSplitScreenMultiWindow
562 * @see #mSupportsFreeformWindowManagement
563 * @see #mSupportsPictureInPicture
564 * @see #mSupportsMultiDisplay
565 */
566 boolean mSupportsMultiWindow;
567 boolean mSupportsSplitScreenMultiWindow;
568 boolean mSupportsFreeformWindowManagement;
569 boolean mSupportsPictureInPicture;
570 boolean mSupportsMultiDisplay;
571 boolean mForceResizableActivities;
572
573 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
574
575 // VR Vr2d Display Id.
576 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700577
Wale Ogunwalef6733932018-06-27 05:14:34 -0700578 /**
579 * Set while we are wanting to sleep, to prevent any
580 * activities from being started/resumed.
581 *
582 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
583 *
584 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
585 * while in the sleep state until there is a pending transition out of sleep, in which case
586 * mSleeping is set to false, and remains false while awake.
587 *
588 * Whether mSleeping can quickly toggled between true/false without the device actually
589 * display changing states is undefined.
590 */
591 private boolean mSleeping = false;
592
593 /**
594 * The process state used for processes that are running the top activities.
595 * This changes between TOP and TOP_SLEEPING to following mSleeping.
596 */
597 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
598
Riddle Hsua0022cd2019-09-09 21:12:41 +0800599 @Retention(RetentionPolicy.SOURCE)
600 @IntDef({
601 LAYOUT_REASON_CONFIG_CHANGED,
602 LAYOUT_REASON_VISIBILITY_CHANGED,
603 })
604 @interface LayoutReason {}
605 static final int LAYOUT_REASON_CONFIG_CHANGED = 0x1;
606 static final int LAYOUT_REASON_VISIBILITY_CHANGED = 0x2;
607
608 /** The reasons to perform surface placement. */
609 @LayoutReason
610 private int mLayoutReasons;
611
Wale Ogunwalef6733932018-06-27 05:14:34 -0700612 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
613 // automatically. Important for devices without direct input devices.
614 private boolean mShowDialogs = true;
615
616 /** Set if we are shutting down the system, similar to sleeping. */
617 boolean mShuttingDown = false;
618
619 /**
620 * We want to hold a wake lock while running a voice interaction session, since
621 * this may happen with the screen off and we need to keep the CPU running to
622 * be able to continue to interact with the user.
623 */
624 PowerManager.WakeLock mVoiceWakeLock;
625
626 /**
627 * Set while we are running a voice interaction. This overrides sleeping while it is active.
628 */
629 IVoiceInteractionSession mRunningVoice;
630
631 /**
632 * The last resumed activity. This is identical to the current resumed activity most
633 * of the time but could be different when we're pausing one activity before we resume
634 * another activity.
635 */
636 ActivityRecord mLastResumedActivity;
637
638 /**
639 * The activity that is currently being traced as the active resumed activity.
640 *
641 * @see #updateResumedAppTrace
642 */
643 private @Nullable ActivityRecord mTracedResumedActivity;
644
645 /** If non-null, we are tracking the time the user spends in the currently focused app. */
646 AppTimeTracker mCurAppTimeTracker;
647
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700648 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700649
Wale Ogunwale53783742018-09-16 10:21:51 -0700650 /**
651 * Packages that the user has asked to have run in screen size
652 * compatibility mode instead of filling the screen.
653 */
654 CompatModePackages mCompatModePackages;
655
Wale Ogunwalef6733932018-06-27 05:14:34 -0700656 private FontScaleSettingObserver mFontScaleSettingObserver;
657
Ricky Wai96f5c352019-04-10 18:40:17 +0100658 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000659
Wale Ogunwalef6733932018-06-27 05:14:34 -0700660 private final class FontScaleSettingObserver extends ContentObserver {
661 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
662 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
663
664 public FontScaleSettingObserver() {
665 super(mH);
666 final ContentResolver resolver = mContext.getContentResolver();
667 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
668 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
669 UserHandle.USER_ALL);
670 }
671
672 @Override
673 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
674 if (mFontScaleUri.equals(uri)) {
675 updateFontScaleIfNeeded(userId);
676 } else if (mHideErrorDialogsUri.equals(uri)) {
677 synchronized (mGlobalLock) {
678 updateShouldShowDialogsLocked(getGlobalConfiguration());
679 }
680 }
681 }
682 }
683
Riddle Hsua0536432019-02-16 00:38:59 +0800684 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
685 @Target(ElementType.METHOD)
686 @Retention(RetentionPolicy.SOURCE)
687 @interface HotPath {
688 int NONE = 0;
689 int OOM_ADJUSTMENT = 1;
690 int LRU_UPDATE = 2;
691 int PROCESS_CHANGE = 3;
692 int caller() default NONE;
693 }
694
Charles Chen8d98dd22018-12-26 17:36:54 +0800695 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
696 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700697 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700698 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700699 mSystemThread = ActivityThread.currentActivityThread();
700 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700701 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800702 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700703 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700704 }
705
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700706 public void onSystemReady() {
707 synchronized (mGlobalLock) {
708 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
709 PackageManager.FEATURE_CANT_SAVE_STATE);
710 mAssistUtils = new AssistUtils(mContext);
711 mVrController.onSystemReady();
712 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700713 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700714 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700715 }
716
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700717 public void onInitPowerManagement() {
718 synchronized (mGlobalLock) {
719 mStackSupervisor.initPowerManagement();
720 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
721 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
722 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
723 mVoiceWakeLock.setReferenceCounted(false);
724 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700725 }
726
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700727 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700728 mFontScaleSettingObserver = new FontScaleSettingObserver();
729 }
730
Wale Ogunwale59507092018-10-29 09:00:30 -0700731 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732 final boolean freeformWindowManagement =
733 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
734 || Settings.Global.getInt(
735 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
736
737 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
738 final boolean supportsPictureInPicture = supportsMultiWindow &&
739 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
740 final boolean supportsSplitScreenMultiWindow =
741 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
742 final boolean supportsMultiDisplay = mContext.getPackageManager()
743 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700744 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
745 final boolean forceResizable = Settings.Global.getInt(
746 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
747
748 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900749 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700750
751 final Configuration configuration = new Configuration();
752 Settings.System.getConfiguration(resolver, configuration);
753 if (forceRtl) {
754 // This will take care of setting the correct layout direction flags
755 configuration.setLayoutDirection(configuration.locale);
756 }
757
758 synchronized (mGlobalLock) {
759 mForceResizableActivities = forceResizable;
760 final boolean multiWindowFormEnabled = freeformWindowManagement
761 || supportsSplitScreenMultiWindow
762 || supportsPictureInPicture
763 || supportsMultiDisplay;
764 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
765 mSupportsMultiWindow = true;
766 mSupportsFreeformWindowManagement = freeformWindowManagement;
767 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
768 mSupportsPictureInPicture = supportsPictureInPicture;
769 mSupportsMultiDisplay = supportsMultiDisplay;
770 } else {
771 mSupportsMultiWindow = false;
772 mSupportsFreeformWindowManagement = false;
773 mSupportsSplitScreenMultiWindow = false;
774 mSupportsPictureInPicture = false;
775 mSupportsMultiDisplay = false;
776 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700777 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 // This happens before any activities are started, so we can change global configuration
779 // in-place.
780 updateConfigurationLocked(configuration, null, true);
781 final Configuration globalConfig = getGlobalConfiguration();
782 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
783
784 // Load resources only after the current configuration has been set.
785 final Resources res = mContext.getResources();
786 mThumbnailWidth = res.getDimensionPixelSize(
787 com.android.internal.R.dimen.thumbnail_width);
788 mThumbnailHeight = res.getDimensionPixelSize(
789 com.android.internal.R.dimen.thumbnail_height);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700790 }
791 }
792
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800793 public WindowManagerGlobalLock getGlobalLock() {
794 return mGlobalLock;
795 }
796
Yunfan Chen585f2932019-01-29 16:04:45 +0900797 /** For test purpose only. */
798 @VisibleForTesting
799 public ActivityTaskManagerInternal getAtmInternal() {
800 return mInternal;
801 }
802
Riddle Hsud93a6c42018-11-29 21:50:06 +0800803 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
804 Looper looper) {
805 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700808 final File systemDir = SystemServiceManager.ensureSystemDir();
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800809 mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
Wale Ogunwale53783742018-09-16 10:21:51 -0700810 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700812
813 mTempConfig.setToDefaults();
814 mTempConfig.setLocales(LocaleList.getDefault());
815 mConfigurationSeq = mTempConfig.seq = 1;
816 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800817 mRootActivityContainer = new RootActivityContainer(this);
818 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700822 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700824 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700825 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700826 mKeyguardController = mStackSupervisor.getKeyguardController();
827 }
828
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700829 public void onActivityManagerInternalAdded() {
830 synchronized (mGlobalLock) {
831 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
832 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
833 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700834 }
835
Yunfan Chen75157d72018-07-27 14:47:21 +0900836 int increaseConfigurationSeqLocked() {
837 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
838 return mConfigurationSeq;
839 }
840
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700841 protected ActivityStackSupervisor createStackSupervisor() {
842 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
843 supervisor.initialize();
844 return supervisor;
845 }
846
Wale Ogunwaleda8b8272018-11-29 19:37:37 -0800847 protected AppWarnings createAppWarnings(
848 Context uiContext, Handler handler, Handler uiHandler, File systemDir) {
849 return new AppWarnings(this, uiContext, handler, uiHandler, systemDir);
850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setWindowManager(WindowManagerService wm) {
853 synchronized (mGlobalLock) {
854 mWindowManager = wm;
855 mLockTaskController.setWindowManager(wm);
856 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800857 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700858 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700859 }
860
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700861 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
862 synchronized (mGlobalLock) {
863 mUsageStatsInternal = usageStatsManager;
864 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700865 }
866
Wale Ogunwalef6733932018-06-27 05:14:34 -0700867 UserManagerService getUserManager() {
868 if (mUserManager == null) {
869 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
870 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
871 }
872 return mUserManager;
873 }
874
875 AppOpsService getAppOpsService() {
876 if (mAppOpsService == null) {
877 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
878 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
879 }
880 return mAppOpsService;
881 }
882
883 boolean hasUserRestriction(String restriction, int userId) {
884 return getUserManager().hasUserRestriction(restriction, userId);
885 }
886
Michal Karpinski15486842019-04-25 17:33:42 +0100887 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
888 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
889 callingUid, callingPackage);
890 if (mode == AppOpsManager.MODE_DEFAULT) {
891 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
892 == PERMISSION_GRANTED;
893 }
894 return mode == AppOpsManager.MODE_ALLOWED;
895 }
896
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700897 @VisibleForTesting
898 protected void setRecentTasks(RecentTasks recentTasks) {
899 mRecentTasks = recentTasks;
900 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700901 }
902
903 RecentTasks getRecentTasks() {
904 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700905 }
906
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700907 ClientLifecycleManager getLifecycleManager() {
908 return mLifecycleManager;
909 }
910
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700911 ActivityStartController getActivityStartController() {
912 return mActivityStartController;
913 }
914
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700915 TaskChangeNotificationController getTaskChangeNotificationController() {
916 return mTaskChangeNotificationController;
917 }
918
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700919 LockTaskController getLockTaskController() {
920 return mLockTaskController;
921 }
922
Yunfan Chen75157d72018-07-27 14:47:21 +0900923 /**
924 * Return the global configuration used by the process corresponding to the input pid. This is
925 * usually the global configuration with some overrides specific to that process.
926 */
927 Configuration getGlobalConfigurationForCallingPid() {
928 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800929 return getGlobalConfigurationForPid(pid);
930 }
931
932 /**
933 * Return the global configuration used by the process corresponding to the given pid.
934 */
935 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900936 if (pid == MY_PID || pid < 0) {
937 return getGlobalConfiguration();
938 }
939 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100940 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900941 return app != null ? app.getConfiguration() : getGlobalConfiguration();
942 }
943 }
944
945 /**
946 * Return the device configuration info used by the process corresponding to the input pid.
947 * The value is consistent with the global configuration for the process.
948 */
949 @Override
950 public ConfigurationInfo getDeviceConfigurationInfo() {
951 ConfigurationInfo config = new ConfigurationInfo();
952 synchronized (mGlobalLock) {
953 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
954 config.reqTouchScreen = globalConfig.touchscreen;
955 config.reqKeyboardType = globalConfig.keyboard;
956 config.reqNavigation = globalConfig.navigation;
957 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
958 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
959 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
960 }
961 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
962 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
963 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
964 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700965 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900966 }
967 return config;
968 }
969
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700970 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700971 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700972 }
973
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700974 public static final class Lifecycle extends SystemService {
975 private final ActivityTaskManagerService mService;
976
977 public Lifecycle(Context context) {
978 super(context);
979 mService = new ActivityTaskManagerService(context);
980 }
981
982 @Override
983 public void onStart() {
984 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700985 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700986 }
987
Garfield Tan891146c2018-10-09 12:14:00 -0700988 @Override
989 public void onUnlockUser(int userId) {
990 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800991 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700992 }
993 }
994
995 @Override
996 public void onCleanupUser(int userId) {
997 synchronized (mService.getGlobalLock()) {
998 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
999 }
1000 }
1001
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001002 public ActivityTaskManagerService getService() {
1003 return mService;
1004 }
1005 }
1006
1007 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001008 public final int startActivity(IApplicationThread caller, String callingPackage,
1009 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1010 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1011 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1012 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1013 UserHandle.getCallingUserId());
1014 }
1015
1016 @Override
1017 public final int startActivities(IApplicationThread caller, String callingPackage,
1018 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1019 int userId) {
1020 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001021 enforceNotIsolatedCaller(reason);
1022 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001024 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1025 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1026 reason, null /* originatingPendingIntent */,
1027 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001028 }
1029
1030 @Override
1031 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1032 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1033 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1034 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1035 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1036 true /*validateIncomingUser*/);
1037 }
1038
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001039 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1041 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1042 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001043 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001045 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001046 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1047
1048 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001049 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001050 .setCaller(caller)
1051 .setCallingPackage(callingPackage)
1052 .setResolvedType(resolvedType)
1053 .setResultTo(resultTo)
1054 .setResultWho(resultWho)
1055 .setRequestCode(requestCode)
1056 .setStartFlags(startFlags)
1057 .setProfilerInfo(profilerInfo)
1058 .setActivityOptions(bOptions)
1059 .setMayWait(userId)
1060 .execute();
1061
1062 }
1063
1064 @Override
1065 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1066 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001067 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1068 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001069 // Refuse possible leaked file descriptors
1070 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1071 throw new IllegalArgumentException("File descriptors passed in Intent");
1072 }
1073
1074 if (!(target instanceof PendingIntentRecord)) {
1075 throw new IllegalArgumentException("Bad PendingIntent object");
1076 }
1077
1078 PendingIntentRecord pir = (PendingIntentRecord)target;
1079
1080 synchronized (mGlobalLock) {
1081 // If this is coming from the currently resumed activity, it is
1082 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001083 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 if (stack.mResumedActivity != null &&
1085 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001086 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001087 }
1088 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001089 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 }
1092
1093 @Override
1094 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1095 Bundle bOptions) {
1096 // Refuse possible leaked file descriptors
1097 if (intent != null && intent.hasFileDescriptors()) {
1098 throw new IllegalArgumentException("File descriptors passed in Intent");
1099 }
1100 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1101
1102 synchronized (mGlobalLock) {
1103 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1104 if (r == null) {
1105 SafeActivityOptions.abort(options);
1106 return false;
1107 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001108 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001109 // The caller is not running... d'oh!
1110 SafeActivityOptions.abort(options);
1111 return false;
1112 }
1113 intent = new Intent(intent);
1114 // The caller is not allowed to change the data.
1115 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1116 // And we are resetting to find the next component...
1117 intent.setComponent(null);
1118
1119 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1120
1121 ActivityInfo aInfo = null;
1122 try {
1123 List<ResolveInfo> resolves =
1124 AppGlobals.getPackageManager().queryIntentActivities(
1125 intent, r.resolvedType,
1126 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1127 UserHandle.getCallingUserId()).getList();
1128
1129 // Look for the original activity in the list...
1130 final int N = resolves != null ? resolves.size() : 0;
1131 for (int i=0; i<N; i++) {
1132 ResolveInfo rInfo = resolves.get(i);
1133 if (rInfo.activityInfo.packageName.equals(r.packageName)
1134 && rInfo.activityInfo.name.equals(r.info.name)) {
1135 // We found the current one... the next matching is
1136 // after it.
1137 i++;
1138 if (i<N) {
1139 aInfo = resolves.get(i).activityInfo;
1140 }
1141 if (debug) {
1142 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1143 + "/" + r.info.name);
1144 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1145 ? "null" : aInfo.packageName + "/" + aInfo.name));
1146 }
1147 break;
1148 }
1149 }
1150 } catch (RemoteException e) {
1151 }
1152
1153 if (aInfo == null) {
1154 // Nobody who is next!
1155 SafeActivityOptions.abort(options);
1156 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1157 return false;
1158 }
1159
1160 intent.setComponent(new ComponentName(
1161 aInfo.applicationInfo.packageName, aInfo.name));
1162 intent.setFlags(intent.getFlags()&~(
1163 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1164 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1165 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1166 FLAG_ACTIVITY_NEW_TASK));
1167
1168 // Okay now we need to start the new activity, replacing the currently running activity.
1169 // This is a little tricky because we want to start the new one as if the current one is
1170 // finished, but not finish the current one first so that there is no flicker.
1171 // And thus...
1172 final boolean wasFinishing = r.finishing;
1173 r.finishing = true;
1174
1175 // Propagate reply information over to the new activity.
1176 final ActivityRecord resultTo = r.resultTo;
1177 final String resultWho = r.resultWho;
1178 final int requestCode = r.requestCode;
1179 r.resultTo = null;
1180 if (resultTo != null) {
1181 resultTo.removeResultsLocked(r, resultWho, requestCode);
1182 }
1183
1184 final long origId = Binder.clearCallingIdentity();
1185 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001186 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001187 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001188 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001189 .setResolvedType(r.resolvedType)
1190 .setActivityInfo(aInfo)
1191 .setResultTo(resultTo != null ? resultTo.appToken : null)
1192 .setResultWho(resultWho)
1193 .setRequestCode(requestCode)
1194 .setCallingPid(-1)
1195 .setCallingUid(r.launchedFromUid)
1196 .setCallingPackage(r.launchedFromPackage)
1197 .setRealCallingPid(-1)
1198 .setRealCallingUid(r.launchedFromUid)
1199 .setActivityOptions(options)
1200 .execute();
1201 Binder.restoreCallingIdentity(origId);
1202
1203 r.finishing = wasFinishing;
1204 if (res != ActivityManager.START_SUCCESS) {
1205 return false;
1206 }
1207 return true;
1208 }
1209 }
1210
1211 @Override
1212 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1213 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1214 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1215 final WaitResult res = new WaitResult();
1216 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001217 enforceNotIsolatedCaller("startActivityAndWait");
1218 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1219 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001221 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 .setCaller(caller)
1223 .setCallingPackage(callingPackage)
1224 .setResolvedType(resolvedType)
1225 .setResultTo(resultTo)
1226 .setResultWho(resultWho)
1227 .setRequestCode(requestCode)
1228 .setStartFlags(startFlags)
1229 .setActivityOptions(bOptions)
1230 .setMayWait(userId)
1231 .setProfilerInfo(profilerInfo)
1232 .setWaitResult(res)
1233 .execute();
1234 }
1235 return res;
1236 }
1237
1238 @Override
1239 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1240 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1241 int startFlags, Configuration config, Bundle bOptions, int userId) {
1242 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001243 enforceNotIsolatedCaller("startActivityWithConfig");
1244 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1245 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001246 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001247 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001248 .setCaller(caller)
1249 .setCallingPackage(callingPackage)
1250 .setResolvedType(resolvedType)
1251 .setResultTo(resultTo)
1252 .setResultWho(resultWho)
1253 .setRequestCode(requestCode)
1254 .setStartFlags(startFlags)
1255 .setGlobalConfiguration(config)
1256 .setActivityOptions(bOptions)
1257 .setMayWait(userId)
1258 .execute();
1259 }
1260 }
1261
Alison Cichowlas3e340502018-08-07 17:15:01 -04001262
1263 @Override
1264 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1265 int callingUid = Binder.getCallingUid();
1266 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1267 throw new SecurityException("Only the system process can request a permission token, "
1268 + "received request from uid: " + callingUid);
1269 }
1270 IBinder permissionToken = new Binder();
1271 synchronized (mGlobalLock) {
1272 mStartActivitySources.put(permissionToken, delegatorToken);
1273 }
1274
1275 Message expireMsg = PooledLambda.obtainMessage(
1276 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1277 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1278
1279 Message forgetMsg = PooledLambda.obtainMessage(
1280 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1281 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1282
1283 return permissionToken;
1284 }
1285
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 @Override
1287 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1288 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001289 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1290 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001292 // permission grants) as any app that may launch one of your own activities. So we only
1293 // allow this in two cases:
1294 // 1) The caller is an activity that is part of the core framework, and then only when it
1295 // is running as the system.
1296 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1297 // can only be requested by a system activity, which may then delegate this call to
1298 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 final ActivityRecord sourceRecord;
1300 final int targetUid;
1301 final String targetPackage;
1302 final boolean isResolver;
1303 synchronized (mGlobalLock) {
1304 if (resultTo == null) {
1305 throw new SecurityException("Must be called from an activity");
1306 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001307 final IBinder sourceToken;
1308 if (permissionToken != null) {
1309 // To even attempt to use a permissionToken, an app must also have this signature
1310 // permission.
1311 mAmInternal.enforceCallingPermission(
1312 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1313 "startActivityAsCaller");
1314 // If called with a permissionToken, we want the sourceRecord from the delegator
1315 // activity that requested this token.
1316 sourceToken = mStartActivitySources.remove(permissionToken);
1317 if (sourceToken == null) {
1318 // Invalid permissionToken, check if it recently expired.
1319 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1320 throw new SecurityException("Called with expired permission token: "
1321 + permissionToken);
1322 } else {
1323 throw new SecurityException("Called with invalid permission token: "
1324 + permissionToken);
1325 }
1326 }
1327 } else {
1328 // This method was called directly by the source.
1329 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331
Wale Ogunwaled32da472018-11-16 07:19:28 -08001332 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333 if (sourceRecord == null) {
1334 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 }
1336 if (sourceRecord.app == null) {
1337 throw new SecurityException("Called without a process attached to activity");
1338 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001339
1340 // Whether called directly or from a delegate, the source activity must be from the
1341 // android package.
1342 if (!sourceRecord.info.packageName.equals("android")) {
1343 throw new SecurityException("Must be called from an activity that is "
1344 + "declared in the android package");
1345 }
1346
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001347 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 // This is still okay, as long as this activity is running under the
1349 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001350 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001351 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001352 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 + " must be system uid or original calling uid "
1354 + sourceRecord.launchedFromUid);
1355 }
1356 }
1357 if (ignoreTargetSecurity) {
1358 if (intent.getComponent() == null) {
1359 throw new SecurityException(
1360 "Component must be specified with ignoreTargetSecurity");
1361 }
1362 if (intent.getSelector() != null) {
1363 throw new SecurityException(
1364 "Selector not allowed with ignoreTargetSecurity");
1365 }
1366 }
1367 targetUid = sourceRecord.launchedFromUid;
1368 targetPackage = sourceRecord.launchedFromPackage;
1369 isResolver = sourceRecord.isResolverOrChildActivity();
1370 }
1371
1372 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001373 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001374 }
1375
1376 // TODO: Switch to user app stacks here.
1377 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(targetUid)
1380 .setCallingPackage(targetPackage)
1381 .setResolvedType(resolvedType)
1382 .setResultTo(resultTo)
1383 .setResultWho(resultWho)
1384 .setRequestCode(requestCode)
1385 .setStartFlags(startFlags)
1386 .setActivityOptions(bOptions)
1387 .setMayWait(userId)
1388 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1389 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001390 // The target may well be in the background, which would normally prevent it
1391 // from starting an activity. Here we definitely want the start to succeed.
1392 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001393 .execute();
1394 } catch (SecurityException e) {
1395 // XXX need to figure out how to propagate to original app.
1396 // A SecurityException here is generally actually a fault of the original
1397 // calling activity (such as a fairly granting permissions), so propagate it
1398 // back to them.
1399 /*
1400 StringBuilder msg = new StringBuilder();
1401 msg.append("While launching");
1402 msg.append(intent.toString());
1403 msg.append(": ");
1404 msg.append(e.getMessage());
1405 */
1406 throw e;
1407 }
1408 }
1409
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1411 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1412 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1413 }
1414
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 @Override
1416 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1417 Intent intent, String resolvedType, IVoiceInteractionSession session,
1418 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1419 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001420 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 if (session == null || interactor == null) {
1422 throw new NullPointerException("null session or interactor");
1423 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001424 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001425 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001426 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 .setCallingUid(callingUid)
1428 .setCallingPackage(callingPackage)
1429 .setResolvedType(resolvedType)
1430 .setVoiceSession(session)
1431 .setVoiceInteractor(interactor)
1432 .setStartFlags(startFlags)
1433 .setProfilerInfo(profilerInfo)
1434 .setActivityOptions(bOptions)
1435 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001436 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .execute();
1438 }
1439
1440 @Override
1441 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1442 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1444 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001446 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .setCallingUid(callingUid)
1448 .setCallingPackage(callingPackage)
1449 .setResolvedType(resolvedType)
1450 .setActivityOptions(bOptions)
1451 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001452 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 .execute();
1454 }
1455
Riddle Hsu609a8e22019-06-27 16:46:29 -06001456 /**
1457 * Start the recents activity to perform the recents animation.
1458 *
1459 * @param intent The intent to start the recents activity.
1460 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1461 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001463 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1464 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001465 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001467 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468 final long origId = Binder.clearCallingIdentity();
1469 try {
1470 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001471 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1472 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001473 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474
1475 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001476 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001477 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001478 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001479 if (recentsAnimationRunner == null) {
1480 anim.preloadRecentsActivity();
1481 } else {
1482 anim.startRecentsActivity(recentsAnimationRunner);
1483 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(origId);
1487 }
1488 }
1489
1490 @Override
1491 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001492 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 "startActivityFromRecents()");
1494
1495 final int callingPid = Binder.getCallingPid();
1496 final int callingUid = Binder.getCallingUid();
1497 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1498 final long origId = Binder.clearCallingIdentity();
1499 try {
1500 synchronized (mGlobalLock) {
1501 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1502 safeOptions);
1503 }
1504 } finally {
1505 Binder.restoreCallingIdentity(origId);
1506 }
1507 }
1508
1509 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001510 * Public API to check if the client is allowed to start an activity on specified display.
1511 *
1512 * If the target display is private or virtual, some restrictions will apply.
1513 *
1514 * @param displayId Target display id.
1515 * @param intent Intent used to launch the activity.
1516 * @param resolvedType The MIME type of the intent.
1517 * @param userId The id of the user for whom the call is made.
1518 * @return {@code true} if a call to start an activity on the target display should succeed and
1519 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1520 */
1521 @Override
1522 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1523 String resolvedType, int userId) {
1524 final int callingUid = Binder.getCallingUid();
1525 final int callingPid = Binder.getCallingPid();
1526 final long origId = Binder.clearCallingIdentity();
1527
1528 try {
1529 // Collect information about the target of the Intent.
1530 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1531 0 /* startFlags */, null /* profilerInfo */, userId,
1532 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1533 UserHandle.USER_NULL));
1534 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1535
1536 synchronized (mGlobalLock) {
1537 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1538 aInfo);
1539 }
1540 } finally {
1541 Binder.restoreCallingIdentity(origId);
1542 }
1543 }
1544
1545 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 * This is the internal entry point for handling Activity.finish().
1547 *
1548 * @param token The Binder token referencing the Activity we want to finish.
1549 * @param resultCode Result code, if any, from this Activity.
1550 * @param resultData Result data (Intent), if any, from this Activity.
1551 * @param finishTask Whether to finish the task associated with this Activity.
1552 *
1553 * @return Returns true if the activity successfully finished, or false if it is still running.
1554 */
1555 @Override
1556 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1557 int finishTask) {
1558 // Refuse possible leaked file descriptors
1559 if (resultData != null && resultData.hasFileDescriptors()) {
1560 throw new IllegalArgumentException("File descriptors passed in Intent");
1561 }
1562
1563 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001564 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 if (r == null) {
1566 return true;
1567 }
1568 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001569 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001570 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 if (rootR == null) {
1572 Slog.w(TAG, "Finishing task with all activities already finished");
1573 }
1574 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1575 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001576 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 return false;
1578 }
1579
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1581 // We should consolidate.
1582 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001584 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 if (next != null) {
1586 // ask watcher if this is allowed
1587 boolean resumeOK = true;
1588 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001589 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001591 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 Watchdog.getInstance().setActivityController(null);
1593 }
1594
1595 if (!resumeOK) {
1596 Slog.i(TAG, "Not finishing activity because controller resumed");
1597 return false;
1598 }
1599 }
1600 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001601
1602 // note down that the process has finished an activity and is in background activity
1603 // starts grace period
1604 if (r.app != null) {
1605 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1606 }
1607
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001608 final long origId = Binder.clearCallingIdentity();
1609 try {
1610 boolean res;
1611 final boolean finishWithRootActivity =
1612 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1613 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1614 || (finishWithRootActivity && r == rootR)) {
1615 // If requested, remove the task that is associated to this activity only if it
1616 // was the root activity in the task. The result code and data is ignored
1617 // because we don't support returning them across task boundaries. Also, to
1618 // keep backwards compatibility we remove the task from recents when finishing
1619 // task with root activity.
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07001620 res = mStackSupervisor.removeTaskByIdLocked(tr.mTaskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 finishWithRootActivity, "finish-activity");
1622 if (!res) {
1623 Slog.i(TAG, "Removing task failed to finish activity");
1624 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001625 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001626 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001627 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001628 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001629 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001630 if (!res) {
1631 Slog.i(TAG, "Failed to finish by app-request");
1632 }
1633 }
1634 return res;
1635 } finally {
1636 Binder.restoreCallingIdentity(origId);
1637 }
1638 }
1639 }
1640
1641 @Override
1642 public boolean finishActivityAffinity(IBinder token) {
1643 synchronized (mGlobalLock) {
1644 final long origId = Binder.clearCallingIdentity();
1645 try {
1646 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1647 if (r == null) {
1648 return false;
1649 }
1650
1651 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1652 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001653 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654 return false;
1655 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001656 r.finishActivityAffinity();
1657 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 } finally {
1659 Binder.restoreCallingIdentity(origId);
1660 }
1661 }
1662 }
1663
1664 @Override
1665 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1666 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001667 try {
1668 WindowProcessController proc = null;
1669 synchronized (mGlobalLock) {
1670 ActivityStack stack = ActivityRecord.getStackLocked(token);
1671 if (stack == null) {
1672 return;
1673 }
1674 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1675 false /* fromTimeout */, false /* processPausingActivities */, config);
1676 if (r != null) {
1677 proc = r.app;
1678 }
1679 if (stopProfiling && proc != null) {
1680 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 }
1682 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001683 } finally {
1684 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 }
1687
1688 @Override
1689 public final void activityResumed(IBinder token) {
1690 final long origId = Binder.clearCallingIdentity();
1691 synchronized (mGlobalLock) {
1692 ActivityRecord.activityResumedLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 }
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696
1697 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001698 public final void activityTopResumedStateLost() {
1699 final long origId = Binder.clearCallingIdentity();
1700 synchronized (mGlobalLock) {
1701 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1702 }
1703 Binder.restoreCallingIdentity(origId);
1704 }
1705
1706 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707 public final void activityPaused(IBinder token) {
1708 final long origId = Binder.clearCallingIdentity();
1709 synchronized (mGlobalLock) {
1710 ActivityStack stack = ActivityRecord.getStackLocked(token);
1711 if (stack != null) {
1712 stack.activityPausedLocked(token, false);
1713 }
1714 }
1715 Binder.restoreCallingIdentity(origId);
1716 }
1717
1718 @Override
1719 public final void activityStopped(IBinder token, Bundle icicle,
1720 PersistableBundle persistentState, CharSequence description) {
1721 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1722
1723 // Refuse possible leaked file descriptors
1724 if (icicle != null && icicle.hasFileDescriptors()) {
1725 throw new IllegalArgumentException("File descriptors passed in Bundle");
1726 }
1727
1728 final long origId = Binder.clearCallingIdentity();
1729
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 String restartingName = null;
1731 int restartingUid = 0;
1732 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001734 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001735 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001736 if (r.attachedToProcess()
1737 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1738 // The activity was requested to restart from
1739 // {@link #restartActivityProcessIfVisible}.
1740 restartingName = r.app.mName;
1741 restartingUid = r.app.mUid;
1742 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001743 r.activityStoppedLocked(icicle, persistentState, description);
1744 }
1745 }
1746
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001747 if (restartingName != null) {
1748 // In order to let the foreground activity can be restarted with its saved state from
1749 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1750 // until the activity reports stopped with the state. And the activity record will be
1751 // kept because the record state is restarting, then the activity will be restarted
1752 // immediately if it is still the top one.
1753 mStackSupervisor.removeRestartTimeouts(r);
1754 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1755 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001756 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757
1758 Binder.restoreCallingIdentity(origId);
1759 }
1760
1761 @Override
1762 public final void activityDestroyed(IBinder token) {
1763 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1764 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001765 final long origId = Binder.clearCallingIdentity();
1766 try {
1767 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1768 if (activity != null) {
1769 activity.destroyed("activityDestroyed");
1770 }
1771 } finally {
1772 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001773 }
1774 }
1775 }
1776
1777 @Override
1778 public final void activityRelaunched(IBinder token) {
1779 final long origId = Binder.clearCallingIdentity();
1780 synchronized (mGlobalLock) {
1781 mStackSupervisor.activityRelaunchedLocked(token);
1782 }
1783 Binder.restoreCallingIdentity(origId);
1784 }
1785
1786 public final void activitySlept(IBinder token) {
1787 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1788
1789 final long origId = Binder.clearCallingIdentity();
1790
1791 synchronized (mGlobalLock) {
1792 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1793 if (r != null) {
1794 mStackSupervisor.activitySleptLocked(r);
1795 }
1796 }
1797
1798 Binder.restoreCallingIdentity(origId);
1799 }
1800
1801 @Override
1802 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1803 synchronized (mGlobalLock) {
1804 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1805 if (r == null) {
1806 return;
1807 }
1808 final long origId = Binder.clearCallingIdentity();
1809 try {
1810 r.setRequestedOrientation(requestedOrientation);
1811 } finally {
1812 Binder.restoreCallingIdentity(origId);
1813 }
1814 }
1815 }
1816
1817 @Override
1818 public int getRequestedOrientation(IBinder token) {
1819 synchronized (mGlobalLock) {
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001820 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1821 return (r != null)
1822 ? r.getRequestedOrientation() : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001823 }
1824 }
1825
1826 @Override
1827 public void setImmersive(IBinder token, boolean immersive) {
1828 synchronized (mGlobalLock) {
1829 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1830 if (r == null) {
1831 throw new IllegalArgumentException();
1832 }
1833 r.immersive = immersive;
1834
1835 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001836 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001837 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001838 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 }
1840 }
1841 }
1842
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001843 void applyUpdateLockStateLocked(ActivityRecord r) {
1844 // Modifications to the UpdateLock state are done on our handler, outside
1845 // the activity manager's locks. The new state is determined based on the
1846 // state *now* of the relevant activity record. The object is passed to
1847 // the handler solely for logging detail, not to be consulted/modified.
1848 final boolean nextState = r != null && r.immersive;
1849 mH.post(() -> {
1850 if (mUpdateLock.isHeld() != nextState) {
1851 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1852 "Applying new update lock state '" + nextState + "' for " + r);
1853 if (nextState) {
1854 mUpdateLock.acquire();
1855 } else {
1856 mUpdateLock.release();
1857 }
1858 }
1859 });
1860 }
1861
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001862 @Override
1863 public boolean isImmersive(IBinder token) {
1864 synchronized (mGlobalLock) {
1865 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1866 if (r == null) {
1867 throw new IllegalArgumentException();
1868 }
1869 return r.immersive;
1870 }
1871 }
1872
1873 @Override
1874 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001875 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001877 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001878 return (r != null) ? r.immersive : false;
1879 }
1880 }
1881
1882 @Override
1883 public void overridePendingTransition(IBinder token, String packageName,
1884 int enterAnim, int exitAnim) {
1885 synchronized (mGlobalLock) {
1886 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1887 if (self == null) {
1888 return;
1889 }
1890
1891 final long origId = Binder.clearCallingIdentity();
1892
1893 if (self.isState(
1894 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001895 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001896 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001897 }
1898
1899 Binder.restoreCallingIdentity(origId);
1900 }
1901 }
1902
1903 @Override
1904 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001905 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001907 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001908 if (r == null) {
1909 return ActivityManager.COMPAT_MODE_UNKNOWN;
1910 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001911 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001912 }
1913 }
1914
1915 @Override
1916 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001917 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001918 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001919 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001921 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 if (r == null) {
1923 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1924 return;
1925 }
1926 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001927 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930
1931 @Override
1932 public int getLaunchedFromUid(IBinder activityToken) {
1933 ActivityRecord srec;
1934 synchronized (mGlobalLock) {
1935 srec = ActivityRecord.forTokenLocked(activityToken);
1936 }
1937 if (srec == null) {
1938 return -1;
1939 }
1940 return srec.launchedFromUid;
1941 }
1942
1943 @Override
1944 public String getLaunchedFromPackage(IBinder activityToken) {
1945 ActivityRecord srec;
1946 synchronized (mGlobalLock) {
1947 srec = ActivityRecord.forTokenLocked(activityToken);
1948 }
1949 if (srec == null) {
1950 return null;
1951 }
1952 return srec.launchedFromPackage;
1953 }
1954
1955 @Override
1956 public boolean convertFromTranslucent(IBinder token) {
1957 final long origId = Binder.clearCallingIdentity();
1958 try {
1959 synchronized (mGlobalLock) {
1960 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1961 if (r == null) {
1962 return false;
1963 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001964 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001965 }
1966 } finally {
1967 Binder.restoreCallingIdentity(origId);
1968 }
1969 }
1970
1971 @Override
1972 public boolean convertToTranslucent(IBinder token, Bundle options) {
1973 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1974 final long origId = Binder.clearCallingIdentity();
1975 try {
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1978 if (r == null) {
1979 return false;
1980 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001981 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001982 int index = task.mActivities.lastIndexOf(r);
1983 if (index > 0) {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02001984 ActivityRecord under = task.getChildAt(index - 1);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001985 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1986 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001987 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 }
1989 } finally {
1990 Binder.restoreCallingIdentity(origId);
1991 }
1992 }
1993
1994 @Override
1995 public void notifyActivityDrawn(IBinder token) {
1996 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1997 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001998 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001999 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002000 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002001 }
2002 }
2003 }
2004
2005 @Override
2006 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2007 synchronized (mGlobalLock) {
2008 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2009 if (r == null) {
2010 return;
2011 }
2012 r.reportFullyDrawnLocked(restoredFromBundle);
2013 }
2014 }
2015
2016 @Override
2017 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2018 synchronized (mGlobalLock) {
2019 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2020 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2021 return stack.mDisplayId;
2022 }
2023 return DEFAULT_DISPLAY;
2024 }
2025 }
2026
2027 @Override
2028 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002029 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 long ident = Binder.clearCallingIdentity();
2031 try {
2032 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002033 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002035 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002036 }
2037 return null;
2038 }
2039 } finally {
2040 Binder.restoreCallingIdentity(ident);
2041 }
2042 }
2043
2044 @Override
2045 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002046 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2048 final long callingId = Binder.clearCallingIdentity();
2049 try {
2050 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 if (stack == null) {
2053 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2054 return;
2055 }
2056 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002057 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002058 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 }
2060 }
2061 } finally {
2062 Binder.restoreCallingIdentity(callingId);
2063 }
2064 }
2065
2066 @Override
2067 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002068 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002069 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2070 final long callingId = Binder.clearCallingIdentity();
2071 try {
2072 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002073 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002074 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002075 if (task == null) {
2076 return;
2077 }
2078 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002079 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002080 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 }
2082 }
2083 } finally {
2084 Binder.restoreCallingIdentity(callingId);
2085 }
2086 }
2087
2088 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002089 public void restartActivityProcessIfVisible(IBinder activityToken) {
2090 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2091 final long callingId = Binder.clearCallingIdentity();
2092 try {
2093 synchronized (mGlobalLock) {
2094 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2095 if (r == null) {
2096 return;
2097 }
2098 r.restartProcessIfVisible();
2099 }
2100 } finally {
2101 Binder.restoreCallingIdentity(callingId);
2102 }
2103 }
2104
2105 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002107 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 synchronized (mGlobalLock) {
2109 final long ident = Binder.clearCallingIdentity();
2110 try {
2111 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2112 "remove-task");
2113 } finally {
2114 Binder.restoreCallingIdentity(ident);
2115 }
2116 }
2117 }
2118
2119 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002120 public void removeAllVisibleRecentTasks() {
2121 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2122 synchronized (mGlobalLock) {
2123 final long ident = Binder.clearCallingIdentity();
2124 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002125 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002126 } finally {
2127 Binder.restoreCallingIdentity(ident);
2128 }
2129 }
2130 }
2131
2132 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2134 synchronized (mGlobalLock) {
2135 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2136 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002137 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002138 }
2139 }
2140 return false;
2141 }
2142
2143 @Override
2144 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2145 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002146
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002147 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002148 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2149 if (r != null) {
2150 return r.getActivityStack().navigateUpToLocked(
2151 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002152 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002153 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002154 }
2155 }
2156
2157 /**
2158 * Attempts to move a task backwards in z-order (the order of activities within the task is
2159 * unchanged).
2160 *
2161 * There are several possible results of this call:
2162 * - if the task is locked, then we will show the lock toast
2163 * - if there is a task behind the provided task, then that task is made visible and resumed as
2164 * this task is moved to the back
2165 * - otherwise, if there are no other tasks in the stack:
2166 * - if this task is in the pinned stack, then we remove the stack completely, which will
2167 * have the effect of moving the task to the top or bottom of the fullscreen stack
2168 * (depending on whether it is visible)
2169 * - otherwise, we simply return home and hide this task
2170 *
2171 * @param token A reference to the activity we wish to move
2172 * @param nonRoot If false then this only works if the activity is the root
2173 * of a task; if true it will work for any activity in a task.
2174 * @return Returns true if the move completed, false if not.
2175 */
2176 @Override
2177 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002178 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 synchronized (mGlobalLock) {
2180 final long origId = Binder.clearCallingIdentity();
2181 try {
2182 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002183 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002184 if (task != null) {
2185 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2186 }
2187 } finally {
2188 Binder.restoreCallingIdentity(origId);
2189 }
2190 }
2191 return false;
2192 }
2193
2194 @Override
2195 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002196 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 long ident = Binder.clearCallingIdentity();
2198 Rect rect = new Rect();
2199 try {
2200 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002201 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002202 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2203 if (task == null) {
2204 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2205 return rect;
2206 }
2207 if (task.getStack() != null) {
2208 // Return the bounds from window manager since it will be adjusted for various
2209 // things like the presense of a docked stack for tasks that aren't resizeable.
2210 task.getWindowContainerBounds(rect);
2211 } else {
2212 // Task isn't in window manager yet since it isn't associated with a stack.
2213 // Return the persist value from activity manager
2214 if (!task.matchParentBounds()) {
2215 rect.set(task.getBounds());
2216 } else if (task.mLastNonFullscreenBounds != null) {
2217 rect.set(task.mLastNonFullscreenBounds);
2218 }
2219 }
2220 }
2221 } finally {
2222 Binder.restoreCallingIdentity(ident);
2223 }
2224 return rect;
2225 }
2226
2227 @Override
2228 public ActivityManager.TaskDescription getTaskDescription(int id) {
2229 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002230 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002231 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002232 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2234 if (tr != null) {
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07002235 return tr.mTaskDescription;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 }
2237 }
2238 return null;
2239 }
2240
2241 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002242 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2243 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2244 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2245 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2246 return;
2247 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002248 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 synchronized (mGlobalLock) {
2250 final long ident = Binder.clearCallingIdentity();
2251 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002252 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002253 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002254 if (task == null) {
2255 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2256 return;
2257 }
2258
2259 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2260 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2261
2262 if (!task.isActivityTypeStandardOrUndefined()) {
2263 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2264 + " non-standard task " + taskId + " to windowing mode="
2265 + windowingMode);
2266 }
2267
2268 final ActivityStack stack = task.getStack();
2269 if (toTop) {
2270 stack.moveToFront("setTaskWindowingMode", task);
2271 }
2272 stack.setWindowingMode(windowingMode);
2273 } finally {
2274 Binder.restoreCallingIdentity(ident);
2275 }
2276 }
2277 }
2278
2279 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002281 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002282 ActivityRecord r = getCallingRecordLocked(token);
2283 return r != null ? r.info.packageName : null;
2284 }
2285 }
2286
2287 @Override
2288 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002289 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002290 ActivityRecord r = getCallingRecordLocked(token);
2291 return r != null ? r.intent.getComponent() : null;
2292 }
2293 }
2294
2295 private ActivityRecord getCallingRecordLocked(IBinder token) {
2296 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2297 if (r == null) {
2298 return null;
2299 }
2300 return r.resultTo;
2301 }
2302
2303 @Override
2304 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306
2307 synchronized (mGlobalLock) {
2308 final long origId = Binder.clearCallingIdentity();
2309 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002310 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002311 } finally {
2312 Binder.restoreCallingIdentity(origId);
2313 }
2314 }
2315 }
2316
Mark Renouf446251d2019-04-26 10:22:41 -04002317 @Override
2318 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2319 synchronized (mGlobalLock) {
2320 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2321 if (r == null) {
2322 return;
2323 }
2324 ActivityStack stack = r.getActivityStack();
2325 if (stack != null && stack.isSingleTaskInstance()) {
2326 // Single-task stacks are used for activities which are presented in floating
2327 // windows above full screen activities. Instead of directly finishing the
2328 // task, a task change listener is used to notify SystemUI so the action can be
2329 // handled specially.
2330 final TaskRecord task = r.getTaskRecord();
2331 mTaskChangeNotificationController
2332 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2333 } else {
2334 try {
2335 callback.requestFinish();
2336 } catch (RemoteException e) {
2337 Slog.e(TAG, "Failed to invoke request finish callback", e);
2338 }
2339 }
2340 }
2341 }
2342
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343 /**
2344 * TODO: Add mController hook
2345 */
2346 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002347 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2348 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002349 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350
2351 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2352 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2354 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 }
2356 }
2357
Ricky Waiaca8a772019-04-04 16:01:06 +01002358 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2359 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002361
Ricky Waiaca8a772019-04-04 16:01:06 +01002362 final int callingPid = Binder.getCallingPid();
2363 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002364 if (!isSameApp(callingUid, callingPackage)) {
2365 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2366 + Binder.getCallingPid() + " as package " + callingPackage;
2367 Slog.w(TAG, msg);
2368 throw new SecurityException(msg);
2369 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002371 SafeActivityOptions.abort(options);
2372 return;
2373 }
2374 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 WindowProcessController callerApp = null;
2376 if (appThread != null) {
2377 callerApp = getProcessController(appThread);
2378 }
2379 final ActivityStarter starter = getActivityStartController().obtainStarter(
2380 null /* intent */, "moveTaskToFront");
2381 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2382 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002383 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002384 return;
2385 }
2386 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002388 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002389 if (task == null) {
2390 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002391 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 return;
2393 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002394 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002396 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002397 return;
2398 }
2399 ActivityOptions realOptions = options != null
2400 ? options.getOptions(mStackSupervisor)
2401 : null;
2402 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2403 false /* forceNonResizable */);
2404
2405 final ActivityRecord topActivity = task.getTopActivity();
2406 if (topActivity != null) {
2407
2408 // We are reshowing a task, use a starting window to hide the initial draw delay
2409 // so the transition can start earlier.
2410 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2411 true /* taskSwitch */, fromRecents);
2412 }
2413 } finally {
2414 Binder.restoreCallingIdentity(origId);
2415 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002416 }
2417
Ricky Waiaca8a772019-04-04 16:01:06 +01002418 /**
2419 * Return true if callingUid is system, or packageName belongs to that callingUid.
2420 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002421 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002422 try {
2423 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2424 if (packageName == null) {
2425 return false;
2426 }
2427 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2428 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2429 UserHandle.getUserId(callingUid));
2430 return UserHandle.isSameApp(callingUid, uid);
2431 }
2432 } catch (RemoteException e) {
2433 // Should not happen
2434 }
2435 return true;
2436 }
2437
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002438 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2439 int callingPid, int callingUid, String name) {
2440 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2441 return true;
2442 }
2443
2444 if (getRecentTasks().isCallerRecents(sourceUid)) {
2445 return true;
2446 }
2447
2448 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2449 if (perm == PackageManager.PERMISSION_GRANTED) {
2450 return true;
2451 }
2452 if (checkAllowAppSwitchUid(sourceUid)) {
2453 return true;
2454 }
2455
2456 // If the actual IPC caller is different from the logical source, then
2457 // also see if they are allowed to control app switches.
2458 if (callingUid != -1 && callingUid != sourceUid) {
2459 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2460 if (perm == PackageManager.PERMISSION_GRANTED) {
2461 return true;
2462 }
2463 if (checkAllowAppSwitchUid(callingUid)) {
2464 return true;
2465 }
2466 }
2467
2468 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2469 return false;
2470 }
2471
2472 private boolean checkAllowAppSwitchUid(int uid) {
2473 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2474 if (types != null) {
2475 for (int i = types.size() - 1; i >= 0; i--) {
2476 if (types.valueAt(i).intValue() == uid) {
2477 return true;
2478 }
2479 }
2480 }
2481 return false;
2482 }
2483
2484 @Override
2485 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2486 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2487 "setActivityController()");
2488 synchronized (mGlobalLock) {
2489 mController = controller;
2490 mControllerIsAMonkey = imAMonkey;
2491 Watchdog.getInstance().setActivityController(controller);
2492 }
2493 }
2494
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002495 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 synchronized (mGlobalLock) {
2497 return mController != null && mControllerIsAMonkey;
2498 }
2499 }
2500
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002501 @Override
2502 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2503 synchronized (mGlobalLock) {
2504 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2505 }
2506 }
2507
2508 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002509 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2510 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2511 }
2512
2513 @Override
2514 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2515 @WindowConfiguration.ActivityType int ignoreActivityType,
2516 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2517 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002518 final int callingPid = Binder.getCallingPid();
2519 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002520 final int[] profileIds = getUserManager().getProfileIds(
2521 UserHandle.getUserId(callingUid), true);
2522 ArraySet<Integer> callingProfileIds = new ArraySet<>();
2523 for (int i = 0; i < profileIds.length; i++) {
2524 callingProfileIds.add(profileIds[i]);
2525 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002526 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2527
2528 synchronized (mGlobalLock) {
2529 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2530
Nicholas Sauer0259e532019-08-30 08:24:55 -07002531 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002532 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer3f9249f2019-09-10 20:23:41 -07002533 ignoreWindowingMode, callingUid, allowed, crossUser, callingProfileIds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002534 }
2535
2536 return list;
2537 }
2538
2539 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2541 synchronized (mGlobalLock) {
2542 final long origId = Binder.clearCallingIdentity();
2543 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2544 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002545 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 }
2547 Binder.restoreCallingIdentity(origId);
2548 }
2549 }
2550
2551 @Override
2552 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002553 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 ActivityStack stack = ActivityRecord.getStackLocked(token);
2555 if (stack != null) {
2556 return stack.willActivityBeVisibleLocked(token);
2557 }
2558 return false;
2559 }
2560 }
2561
2562 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002564 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002565 synchronized (mGlobalLock) {
2566 final long ident = Binder.clearCallingIdentity();
2567 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002568 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002569 if (task == null) {
2570 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2571 return;
2572 }
2573
2574 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2575 + " to stackId=" + stackId + " toTop=" + toTop);
2576
Wale Ogunwaled32da472018-11-16 07:19:28 -08002577 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 if (stack == null) {
2579 throw new IllegalStateException(
2580 "moveTaskToStack: No stack for stackId=" + stackId);
2581 }
2582 if (!stack.isActivityTypeStandardOrUndefined()) {
2583 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2584 + taskId + " to stack " + stackId);
2585 }
2586 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002587 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2589 }
2590 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2591 "moveTaskToStack");
2592 } finally {
2593 Binder.restoreCallingIdentity(ident);
2594 }
2595 }
2596 }
2597
2598 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002599 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2600 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002601
2602 final long ident = Binder.clearCallingIdentity();
2603 try {
2604 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002605 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2606 if (stack == null) {
2607 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2608 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002610 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2611 throw new IllegalArgumentException("Stack: " + stackId
2612 + " doesn't support animated resize.");
2613 }
2614 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2615 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616 }
2617 } finally {
2618 Binder.restoreCallingIdentity(ident);
2619 }
2620 }
2621
wilsonshih5c4cf522019-01-25 09:03:47 +08002622 @Override
2623 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2624 int animationDuration) {
2625 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2626
2627 final long ident = Binder.clearCallingIdentity();
2628 try {
2629 synchronized (mGlobalLock) {
2630 if (xOffset == 0 && yOffset == 0) {
2631 return;
2632 }
2633 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2634 if (stack == null) {
2635 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2636 return;
2637 }
2638 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2639 throw new IllegalArgumentException("Stack: " + stackId
2640 + " doesn't support animated resize.");
2641 }
2642 final Rect destBounds = new Rect();
2643 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002644 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002645 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2646 return;
2647 }
2648 destBounds.offset(xOffset, yOffset);
2649 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2650 animationDuration, false /* fromFullscreen */);
2651 }
2652 } finally {
2653 Binder.restoreCallingIdentity(ident);
2654 }
2655 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002656 /**
2657 * Moves the specified task to the primary-split-screen stack.
2658 *
2659 * @param taskId Id of task to move.
2660 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2661 * exist already. See
2662 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2663 * and
2664 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2665 * @param toTop If the task and stack should be moved to the top.
2666 * @param animate Whether we should play an animation for the moving the task.
2667 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2668 * stack. Pass {@code null} to use default bounds.
2669 * @param showRecents If the recents activity should be shown on the other side of the task
2670 * going into split-screen mode.
2671 */
2672 @Override
2673 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2674 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002675 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 "setTaskWindowingModeSplitScreenPrimary()");
2677 synchronized (mGlobalLock) {
2678 final long ident = Binder.clearCallingIdentity();
2679 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002680 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002681 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002682 if (task == null) {
2683 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2684 return false;
2685 }
2686 if (DEBUG_STACK) Slog.d(TAG_STACK,
2687 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2688 + " to createMode=" + createMode + " toTop=" + toTop);
2689 if (!task.isActivityTypeStandardOrUndefined()) {
2690 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2691 + " non-standard task " + taskId + " to split-screen windowing mode");
2692 }
2693
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002694 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002695 final int windowingMode = task.getWindowingMode();
2696 final ActivityStack stack = task.getStack();
2697 if (toTop) {
2698 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2699 }
2700 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002701 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2702 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002703 return windowingMode != task.getWindowingMode();
2704 } finally {
2705 Binder.restoreCallingIdentity(ident);
2706 }
2707 }
2708 }
2709
2710 /**
2711 * Removes stacks in the input windowing modes from the system if they are of activity type
2712 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2713 */
2714 @Override
2715 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002716 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002717 "removeStacksInWindowingModes()");
2718
2719 synchronized (mGlobalLock) {
2720 final long ident = Binder.clearCallingIdentity();
2721 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002722 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727 }
2728
2729 @Override
2730 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002731 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 "removeStacksWithActivityTypes()");
2733
2734 synchronized (mGlobalLock) {
2735 final long ident = Binder.clearCallingIdentity();
2736 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002737 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002738 } finally {
2739 Binder.restoreCallingIdentity(ident);
2740 }
2741 }
2742 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743
2744 @Override
2745 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2746 int userId) {
2747 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002748 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2749 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 final boolean detailed = checkGetTasksPermission(
2752 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2753 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 == PackageManager.PERMISSION_GRANTED;
2755
2756 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002757 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 callingUid);
2759 }
2760 }
2761
2762 @Override
2763 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002764 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 long ident = Binder.clearCallingIdentity();
2766 try {
2767 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002768 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 }
2770 } finally {
2771 Binder.restoreCallingIdentity(ident);
2772 }
2773 }
2774
2775 @Override
2776 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002777 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 long ident = Binder.clearCallingIdentity();
2779 try {
2780 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002781 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002782 }
2783 } finally {
2784 Binder.restoreCallingIdentity(ident);
2785 }
2786 }
2787
2788 @Override
2789 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002790 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 final long callingUid = Binder.getCallingUid();
2792 final long origId = Binder.clearCallingIdentity();
2793 try {
2794 synchronized (mGlobalLock) {
2795 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002796 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2798 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2799 }
2800 } finally {
2801 Binder.restoreCallingIdentity(origId);
2802 }
2803 }
2804
2805 @Override
2806 public void startLockTaskModeByToken(IBinder token) {
2807 synchronized (mGlobalLock) {
2808 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2809 if (r == null) {
2810 return;
2811 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002812 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 }
2814 }
2815
2816 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002817 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002818 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002819 // This makes inner call to look as if it was initiated by system.
2820 long ident = Binder.clearCallingIdentity();
2821 try {
2822 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002823 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002824 MATCH_TASK_IN_STACKS_ONLY);
2825 if (task == null) {
2826 return;
2827 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828
2829 // When starting lock task mode the stack must be in front and focused
2830 task.getStack().moveToFront("startSystemLockTaskMode");
2831 startLockTaskModeLocked(task, true /* isSystemCaller */);
2832 }
2833 } finally {
2834 Binder.restoreCallingIdentity(ident);
2835 }
2836 }
2837
2838 @Override
2839 public void stopLockTaskModeByToken(IBinder token) {
2840 synchronized (mGlobalLock) {
2841 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2842 if (r == null) {
2843 return;
2844 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002845 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002846 }
2847 }
2848
2849 /**
2850 * This API should be called by SystemUI only when user perform certain action to dismiss
2851 * lock task mode. We should only dismiss pinned lock task mode in this case.
2852 */
2853 @Override
2854 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002855 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002856 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2857 }
2858
2859 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2860 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2861 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2862 return;
2863 }
2864
Wale Ogunwaled32da472018-11-16 07:19:28 -08002865 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 if (stack == null || task != stack.topTask()) {
2867 throw new IllegalArgumentException("Invalid task, not in foreground");
2868 }
2869
2870 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2871 // system or a specific app.
2872 // * System-initiated requests will only start the pinned mode (screen pinning)
2873 // * App-initiated requests
2874 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2875 // - will start the pinned mode, otherwise
2876 final int callingUid = Binder.getCallingUid();
2877 long ident = Binder.clearCallingIdentity();
2878 try {
2879 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002880 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002882 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 } finally {
2884 Binder.restoreCallingIdentity(ident);
2885 }
2886 }
2887
2888 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2889 final int callingUid = Binder.getCallingUid();
2890 long ident = Binder.clearCallingIdentity();
2891 try {
2892 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002893 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894 }
2895 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2896 // task and jumping straight into a call in the case of emergency call back.
2897 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2898 if (tm != null) {
2899 tm.showInCallScreen(false);
2900 }
2901 } finally {
2902 Binder.restoreCallingIdentity(ident);
2903 }
2904 }
2905
2906 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002907 public void updateLockTaskPackages(int userId, String[] packages) {
2908 final int callingUid = Binder.getCallingUid();
2909 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2910 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2911 "updateLockTaskPackages()");
2912 }
Riddle Hsu8419e4b2019-09-18 23:28:01 +08002913 synchronized (mGlobalLock) {
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002914 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2915 + Arrays.toString(packages));
2916 getLockTaskController().updateLockTaskPackages(userId, packages);
2917 }
2918 }
2919
2920 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002921 public boolean isInLockTaskMode() {
2922 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2923 }
2924
2925 @Override
2926 public int getLockTaskModeState() {
2927 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002928 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002929 }
2930 }
2931
2932 @Override
2933 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2934 synchronized (mGlobalLock) {
2935 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2936 if (r != null) {
2937 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002938 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002940 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 }
2942 }
2943 }
2944
2945 @Override
2946 public Bundle getActivityOptions(IBinder token) {
2947 final long origId = Binder.clearCallingIdentity();
2948 try {
2949 synchronized (mGlobalLock) {
2950 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2951 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002952 final ActivityOptions activityOptions = r.takeOptionsLocked(
2953 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 return activityOptions == null ? null : activityOptions.toBundle();
2955 }
2956 return null;
2957 }
2958 } finally {
2959 Binder.restoreCallingIdentity(origId);
2960 }
2961 }
2962
2963 @Override
2964 public List<IBinder> getAppTasks(String callingPackage) {
2965 int callingUid = Binder.getCallingUid();
2966 long ident = Binder.clearCallingIdentity();
2967 try {
2968 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002969 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 }
2971 } finally {
2972 Binder.restoreCallingIdentity(ident);
2973 }
2974 }
2975
2976 @Override
2977 public void finishVoiceTask(IVoiceInteractionSession session) {
2978 synchronized (mGlobalLock) {
2979 final long origId = Binder.clearCallingIdentity();
2980 try {
2981 // TODO: VI Consider treating local voice interactions and voice tasks
2982 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002983 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002984 } finally {
2985 Binder.restoreCallingIdentity(origId);
2986 }
2987 }
2988
2989 }
2990
2991 @Override
2992 public boolean isTopOfTask(IBinder token) {
2993 synchronized (mGlobalLock) {
2994 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002995 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 }
2997 }
2998
2999 @Override
3000 public void notifyLaunchTaskBehindComplete(IBinder token) {
3001 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3002 }
3003
3004 @Override
3005 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003006 mH.post(() -> {
3007 synchronized (mGlobalLock) {
3008 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003009 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003011 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003012 } catch (RemoteException e) {
3013 }
3014 }
3015 }
3016
3017 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 }
3019
3020 /** Called from an app when assist data is ready. */
3021 @Override
3022 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3023 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003024 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 synchronized (pae) {
3026 pae.result = extras;
3027 pae.structure = structure;
3028 pae.content = content;
3029 if (referrer != null) {
3030 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3031 }
3032 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003033 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003034 structure.setTaskId(pae.activity.getTaskRecord().mTaskId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003035 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 structure.setHomeActivity(pae.isHome);
3037 }
3038 pae.haveResult = true;
3039 pae.notifyAll();
3040 if (pae.intent == null && pae.receiver == null) {
3041 // Caller is just waiting for the result.
3042 return;
3043 }
3044 }
3045 // We are now ready to launch the assist activity.
3046 IAssistDataReceiver sendReceiver = null;
3047 Bundle sendBundle = null;
3048 synchronized (mGlobalLock) {
3049 buildAssistBundleLocked(pae, extras);
3050 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 if (!exists) {
3053 // Timed out.
3054 return;
3055 }
3056
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003057 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 // Caller wants result sent back to them.
3059 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003060 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003061 pae.activity.getTaskRecord().mTaskId);
Sunny Goyald40c3452019-03-20 12:46:55 -07003062 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3063 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003064 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3065 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3066 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3067 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3068 }
3069 }
3070 if (sendReceiver != null) {
3071 try {
3072 sendReceiver.onHandleAssistData(sendBundle);
3073 } catch (RemoteException e) {
3074 }
3075 return;
3076 }
3077
3078 final long ident = Binder.clearCallingIdentity();
3079 try {
3080 if (TextUtils.equals(pae.intent.getAction(),
3081 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003082 // Start voice interaction through VoiceInteractionManagerService.
3083 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3084 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 } else {
3086 pae.intent.replaceExtras(pae.extras);
3087 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3088 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3089 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003090 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091
3092 try {
3093 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3094 } catch (ActivityNotFoundException e) {
3095 Slog.w(TAG, "No activity to handle assist action.", e);
3096 }
3097 }
3098 } finally {
3099 Binder.restoreCallingIdentity(ident);
3100 }
3101 }
3102
3103 @Override
3104 public int addAppTask(IBinder activityToken, Intent intent,
3105 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3106 final int callingUid = Binder.getCallingUid();
3107 final long callingIdent = Binder.clearCallingIdentity();
3108
3109 try {
3110 synchronized (mGlobalLock) {
3111 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3112 if (r == null) {
3113 throw new IllegalArgumentException("Activity does not exist; token="
3114 + activityToken);
3115 }
3116 ComponentName comp = intent.getComponent();
3117 if (comp == null) {
3118 throw new IllegalArgumentException("Intent " + intent
3119 + " must specify explicit component");
3120 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003121 if (thumbnail.getWidth() != mThumbnailWidth
3122 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 throw new IllegalArgumentException("Bad thumbnail size: got "
3124 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003125 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 }
3127 if (intent.getSelector() != null) {
3128 intent.setSelector(null);
3129 }
3130 if (intent.getSourceBounds() != null) {
3131 intent.setSourceBounds(null);
3132 }
3133 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3134 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3135 // The caller has added this as an auto-remove task... that makes no
3136 // sense, so turn off auto-remove.
3137 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3138 }
3139 }
3140 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3141 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3142 if (ainfo.applicationInfo.uid != callingUid) {
3143 throw new SecurityException(
3144 "Can't add task for another application: target uid="
3145 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3146 }
3147
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003148 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003150 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003152 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 // The app has too many tasks already and we can't add any more
3154 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3155 return INVALID_TASK_ID;
3156 }
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003157 task.mTaskDescription.copyFrom(description);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158
3159 // TODO: Send the thumbnail to WM to store it.
3160
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07003161 return task.mTaskId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 }
3163 } finally {
3164 Binder.restoreCallingIdentity(callingIdent);
3165 }
3166 }
3167
3168 @Override
3169 public Point getAppTaskThumbnailSize() {
3170 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003171 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003172 }
3173 }
3174
3175 @Override
3176 public void setTaskResizeable(int taskId, int resizeableMode) {
3177 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003178 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3180 if (task == null) {
3181 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3182 return;
3183 }
3184 task.setResizeMode(resizeableMode);
3185 }
3186 }
3187
3188 @Override
3189 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003190 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191 long ident = Binder.clearCallingIdentity();
3192 try {
3193 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003194 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003195 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 if (task == null) {
3197 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3198 return;
3199 }
3200 // Place the task in the right stack if it isn't there already based on
3201 // the requested bounds.
3202 // The stack transition logic is:
3203 // - a null bounds on a freeform task moves that task to fullscreen
3204 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3205 // that task to freeform
3206 // - otherwise the task is not moved
3207 ActivityStack stack = task.getStack();
3208 if (!task.getWindowConfiguration().canResizeTask()) {
3209 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3210 }
3211 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3212 stack = stack.getDisplay().getOrCreateStack(
3213 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3214 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3215 stack = stack.getDisplay().getOrCreateStack(
3216 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3217 }
3218
3219 // Reparent the task to the right stack if necessary
3220 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3221 if (stack != task.getStack()) {
3222 // Defer resume until the task is resized below
3223 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3224 DEFER_RESUME, "resizeTask");
3225 preserveWindow = false;
3226 }
3227
3228 // After reparenting (which only resizes the task to the stack bounds), resize the
3229 // task to the actual bounds provided
3230 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3231 }
3232 } finally {
3233 Binder.restoreCallingIdentity(ident);
3234 }
3235 }
3236
3237 @Override
3238 public boolean releaseActivityInstance(IBinder token) {
3239 synchronized (mGlobalLock) {
3240 final long origId = Binder.clearCallingIdentity();
3241 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003242 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3243 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 return false;
3245 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003246 r.destroyImmediately(true /* removeFromApp */, "app-req");
3247 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003248 } finally {
3249 Binder.restoreCallingIdentity(origId);
3250 }
3251 }
3252 }
3253
3254 @Override
3255 public void releaseSomeActivities(IApplicationThread appInt) {
3256 synchronized (mGlobalLock) {
3257 final long origId = Binder.clearCallingIdentity();
3258 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003259 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003260 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 } finally {
3262 Binder.restoreCallingIdentity(origId);
3263 }
3264 }
3265 }
3266
3267 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003268 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003269 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003270 != PackageManager.PERMISSION_GRANTED) {
3271 throw new SecurityException("Requires permission "
3272 + android.Manifest.permission.DEVICE_POWER);
3273 }
3274
3275 synchronized (mGlobalLock) {
3276 long ident = Binder.clearCallingIdentity();
3277 if (mKeyguardShown != keyguardShowing) {
3278 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003279 final Message msg = PooledLambda.obtainMessage(
3280 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3281 keyguardShowing);
3282 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003283 }
3284 try {
wilsonshih177261f2019-02-22 12:02:18 +08003285 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003286 } finally {
3287 Binder.restoreCallingIdentity(ident);
3288 }
3289 }
3290
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003291 mH.post(() -> {
3292 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3293 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3294 }
3295 });
3296 }
3297
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003298 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003299 mH.post(() -> {
3300 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3301 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3302 }
3303 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003304 }
3305
3306 @Override
3307 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003308 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3309 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310
3311 final File passedIconFile = new File(filePath);
3312 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3313 passedIconFile.getName());
3314 if (!legitIconFile.getPath().equals(filePath)
3315 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3316 throw new IllegalArgumentException("Bad file path: " + filePath
3317 + " passed for userId " + userId);
3318 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003319 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003320 }
3321
3322 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003324 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003325 synchronized (mGlobalLock) {
3326 final long ident = Binder.clearCallingIdentity();
3327 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003328 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 if (stack == null) {
3330 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3331 return;
3332 }
3333 if (!stack.isActivityTypeStandardOrUndefined()) {
3334 throw new IllegalArgumentException(
3335 "Removing non-standard stack is not allowed.");
3336 }
3337 mStackSupervisor.removeStack(stack);
3338 } finally {
3339 Binder.restoreCallingIdentity(ident);
3340 }
3341 }
3342 }
3343
3344 @Override
3345 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003346 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347
3348 synchronized (mGlobalLock) {
3349 final long ident = Binder.clearCallingIdentity();
3350 try {
3351 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3352 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003353 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003354 } finally {
3355 Binder.restoreCallingIdentity(ident);
3356 }
3357 }
3358 }
3359
3360 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003361 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003362 synchronized (mGlobalLock) {
3363 long ident = Binder.clearCallingIdentity();
3364 try {
3365 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3366 if (r == null) {
3367 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003368 "toggleFreeformWindowingMode: No activity record matching token="
3369 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 }
3371
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003372 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003373 if (stack == null) {
3374 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3375 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003376 }
3377
Yunfan Chend967af82019-01-17 18:30:18 +09003378 if (!stack.inFreeformWindowingMode()
3379 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3380 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3381 + "toggle between fullscreen and freeform.");
3382 }
3383
3384 if (stack.inFreeformWindowingMode()) {
3385 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003386 } else if (stack.getParent().inFreeformWindowingMode()) {
3387 // If the window is on a freeform display, set it to undefined. It will be
3388 // resolved to freeform and it can adjust windowing mode when the display mode
3389 // changes in runtime.
3390 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003391 } else {
3392 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3393 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 } finally {
3395 Binder.restoreCallingIdentity(ident);
3396 }
3397 }
3398 }
3399
3400 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3401 @Override
3402 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003403 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003404 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003405 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 }
3407
3408 /** Unregister a task stack listener so that it stops receiving callbacks. */
3409 @Override
3410 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003411 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003413 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003414 }
3415
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 @Override
3417 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3418 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3419 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3420 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3421 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3422 }
3423
3424 @Override
3425 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3426 IBinder activityToken, int flags) {
3427 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3428 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3429 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3430 }
3431
3432 @Override
3433 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3434 Bundle args) {
3435 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3436 true /* focused */, true /* newSessionId */, userHandle, args,
3437 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3438 }
3439
3440 @Override
3441 public Bundle getAssistContextExtras(int requestType) {
3442 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3443 null, null, true /* focused */, true /* newSessionId */,
3444 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3445 if (pae == null) {
3446 return null;
3447 }
3448 synchronized (pae) {
3449 while (!pae.haveResult) {
3450 try {
3451 pae.wait();
3452 } catch (InterruptedException e) {
3453 }
3454 }
3455 }
3456 synchronized (mGlobalLock) {
3457 buildAssistBundleLocked(pae, pae.result);
3458 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460 }
3461 return pae.extras;
3462 }
3463
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003464 /**
3465 * Binder IPC calls go through the public entry point.
3466 * This can be called with or without the global lock held.
3467 */
3468 private static int checkCallingPermission(String permission) {
3469 return checkPermission(
3470 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3471 }
3472
3473 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003474 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003475 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3476 mAmInternal.enforceCallingPermission(permission, func);
3477 }
3478 }
3479
3480 @VisibleForTesting
3481 int checkGetTasksPermission(String permission, int pid, int uid) {
3482 return checkPermission(permission, pid, uid);
3483 }
3484
3485 static int checkPermission(String permission, int pid, int uid) {
3486 if (permission == null) {
3487 return PackageManager.PERMISSION_DENIED;
3488 }
3489 return checkComponentPermission(permission, pid, uid, -1, true);
3490 }
3491
Wale Ogunwale214f3482018-10-04 11:00:47 -07003492 public static int checkComponentPermission(String permission, int pid, int uid,
3493 int owningUid, boolean exported) {
3494 return ActivityManagerService.checkComponentPermission(
3495 permission, pid, uid, owningUid, exported);
3496 }
3497
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003498 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3499 if (getRecentTasks().isCallerRecents(callingUid)) {
3500 // Always allow the recents component to get tasks
3501 return true;
3502 }
3503
3504 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3505 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3506 if (!allowed) {
3507 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3508 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3509 // Temporary compatibility: some existing apps on the system image may
3510 // still be requesting the old permission and not switched to the new
3511 // one; if so, we'll still allow them full access. This means we need
3512 // to see if they are holding the old permission and are a system app.
3513 try {
3514 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3515 allowed = true;
3516 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3517 + " is using old GET_TASKS but privileged; allowing");
3518 }
3519 } catch (RemoteException e) {
3520 }
3521 }
3522 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3523 + " does not hold REAL_GET_TASKS; limiting output");
3524 }
3525 return allowed;
3526 }
3527
Nicholas Sauer0259e532019-08-30 08:24:55 -07003528 boolean isCrossUserAllowed(int pid, int uid) {
3529 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3530 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3531 }
3532
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003533 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3534 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3535 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3536 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003537 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 "enqueueAssistContext()");
3539
3540 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003541 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003542 if (activity == null) {
3543 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3544 return null;
3545 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003546 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003547 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3548 return null;
3549 }
3550 if (focused) {
3551 if (activityToken != null) {
3552 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3553 if (activity != caller) {
3554 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3555 + " is not current top " + activity);
3556 return null;
3557 }
3558 }
3559 } else {
3560 activity = ActivityRecord.forTokenLocked(activityToken);
3561 if (activity == null) {
3562 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3563 + " couldn't be found");
3564 return null;
3565 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003566 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003567 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3568 return null;
3569 }
3570 }
3571
3572 PendingAssistExtras pae;
3573 Bundle extras = new Bundle();
3574 if (args != null) {
3575 extras.putAll(args);
3576 }
3577 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003578 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579
3580 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3581 userHandle);
3582 pae.isHome = activity.isActivityTypeHome();
3583
3584 // Increment the sessionId if necessary
3585 if (newSessionId) {
3586 mViSessionId++;
3587 }
3588 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003589 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3590 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003592 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003593 } catch (RemoteException e) {
3594 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3595 return null;
3596 }
3597 return pae;
3598 }
3599 }
3600
3601 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3602 if (result != null) {
3603 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3604 }
3605 if (pae.hint != null) {
3606 pae.extras.putBoolean(pae.hint, true);
3607 }
3608 }
3609
3610 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3611 IAssistDataReceiver receiver;
3612 synchronized (mGlobalLock) {
3613 mPendingAssistExtras.remove(pae);
3614 receiver = pae.receiver;
3615 }
3616 if (receiver != null) {
3617 // Caller wants result sent back to them.
3618 Bundle sendBundle = new Bundle();
3619 // At least return the receiver extras
3620 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3621 try {
3622 pae.receiver.onHandleAssistData(sendBundle);
3623 } catch (RemoteException e) {
3624 }
3625 }
3626 }
3627
3628 public class PendingAssistExtras extends Binder implements Runnable {
3629 public final ActivityRecord activity;
3630 public boolean isHome;
3631 public final Bundle extras;
3632 public final Intent intent;
3633 public final String hint;
3634 public final IAssistDataReceiver receiver;
3635 public final int userHandle;
3636 public boolean haveResult = false;
3637 public Bundle result = null;
3638 public AssistStructure structure = null;
3639 public AssistContent content = null;
3640 public Bundle receiverExtras;
3641
3642 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3643 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3644 int _userHandle) {
3645 activity = _activity;
3646 extras = _extras;
3647 intent = _intent;
3648 hint = _hint;
3649 receiver = _receiver;
3650 receiverExtras = _receiverExtras;
3651 userHandle = _userHandle;
3652 }
3653
3654 @Override
3655 public void run() {
3656 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3657 synchronized (this) {
3658 haveResult = true;
3659 notifyAll();
3660 }
3661 pendingAssistExtrasTimedOut(this);
3662 }
3663 }
3664
3665 @Override
3666 public boolean isAssistDataAllowedOnCurrentActivity() {
3667 int userId;
3668 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003669 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003670 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3671 return false;
3672 }
3673
3674 final ActivityRecord activity = focusedStack.getTopActivity();
3675 if (activity == null) {
3676 return false;
3677 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003678 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003679 }
3680 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3681 }
3682
3683 @Override
3684 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3685 long ident = Binder.clearCallingIdentity();
3686 try {
3687 synchronized (mGlobalLock) {
3688 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003689 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003690 if (top != caller) {
3691 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3692 + " is not current top " + top);
3693 return false;
3694 }
3695 if (!top.nowVisible) {
3696 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3697 + " is not visible");
3698 return false;
3699 }
3700 }
3701 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3702 token);
3703 } finally {
3704 Binder.restoreCallingIdentity(ident);
3705 }
3706 }
3707
3708 @Override
3709 public boolean isRootVoiceInteraction(IBinder token) {
3710 synchronized (mGlobalLock) {
3711 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3712 if (r == null) {
3713 return false;
3714 }
3715 return r.rootVoiceInteraction;
3716 }
3717 }
3718
Wale Ogunwalef6733932018-06-27 05:14:34 -07003719 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3720 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3721 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3722 if (activityToCallback == null) return;
3723 activityToCallback.setVoiceSessionLocked(voiceSession);
3724
3725 // Inform the activity
3726 try {
3727 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3728 voiceInteractor);
3729 long token = Binder.clearCallingIdentity();
3730 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003731 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003732 } finally {
3733 Binder.restoreCallingIdentity(token);
3734 }
3735 // TODO: VI Should we cache the activity so that it's easier to find later
3736 // rather than scan through all the stacks and activities?
3737 } catch (RemoteException re) {
3738 activityToCallback.clearVoiceSessionLocked();
3739 // TODO: VI Should this terminate the voice session?
3740 }
3741 }
3742
3743 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3744 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3745 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3746 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3747 boolean wasRunningVoice = mRunningVoice != null;
3748 mRunningVoice = session;
3749 if (!wasRunningVoice) {
3750 mVoiceWakeLock.acquire();
3751 updateSleepIfNeededLocked();
3752 }
3753 }
3754 }
3755
3756 void finishRunningVoiceLocked() {
3757 if (mRunningVoice != null) {
3758 mRunningVoice = null;
3759 mVoiceWakeLock.release();
3760 updateSleepIfNeededLocked();
3761 }
3762 }
3763
3764 @Override
3765 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3766 synchronized (mGlobalLock) {
3767 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3768 if (keepAwake) {
3769 mVoiceWakeLock.acquire();
3770 } else {
3771 mVoiceWakeLock.release();
3772 }
3773 }
3774 }
3775 }
3776
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003777 @Override
3778 public ComponentName getActivityClassForToken(IBinder token) {
3779 synchronized (mGlobalLock) {
3780 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3781 if (r == null) {
3782 return null;
3783 }
3784 return r.intent.getComponent();
3785 }
3786 }
3787
3788 @Override
3789 public String getPackageForToken(IBinder token) {
3790 synchronized (mGlobalLock) {
3791 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3792 if (r == null) {
3793 return null;
3794 }
3795 return r.packageName;
3796 }
3797 }
3798
3799 @Override
3800 public void showLockTaskEscapeMessage(IBinder token) {
3801 synchronized (mGlobalLock) {
3802 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3803 if (r == null) {
3804 return;
3805 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003806 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003807 }
3808 }
3809
3810 @Override
3811 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003812 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 final long token = Binder.clearCallingIdentity();
3814 try {
3815 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003816 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003817 }
3818 } finally {
3819 Binder.restoreCallingIdentity(token);
3820 }
3821 }
3822
3823 /**
3824 * Try to place task to provided position. The final position might be different depending on
3825 * current user and stacks state. The task will be moved to target stack if it's currently in
3826 * different stack.
3827 */
3828 @Override
3829 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003830 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 synchronized (mGlobalLock) {
3832 long ident = Binder.clearCallingIdentity();
3833 try {
3834 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3835 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003836 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 if (task == null) {
3838 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3839 + taskId);
3840 }
3841
Wale Ogunwaled32da472018-11-16 07:19:28 -08003842 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843
3844 if (stack == null) {
3845 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3846 + stackId);
3847 }
3848 if (!stack.isActivityTypeStandardOrUndefined()) {
3849 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3850 + " the position of task " + taskId + " in/to non-standard stack");
3851 }
3852
3853 // TODO: Have the callers of this API call a separate reparent method if that is
3854 // what they intended to do vs. having this method also do reparenting.
3855 if (task.getStack() == stack) {
3856 // Change position in current stack.
3857 stack.positionChildAt(task, position);
3858 } else {
3859 // Reparent to new stack.
3860 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3861 !DEFER_RESUME, "positionTaskInStack");
3862 }
3863 } finally {
3864 Binder.restoreCallingIdentity(ident);
3865 }
3866 }
3867 }
3868
3869 @Override
3870 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3871 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3872 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003873 + Arrays.toString(horizontalSizeConfiguration) + " "
3874 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003875 synchronized (mGlobalLock) {
3876 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3877 if (record == null) {
3878 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3879 + "found for: " + token);
3880 }
3881 record.setSizeConfigurations(horizontalSizeConfiguration,
3882 verticalSizeConfigurations, smallestSizeConfigurations);
3883 }
3884 }
3885
3886 /**
3887 * Dismisses split-screen multi-window mode.
3888 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3889 */
3890 @Override
3891 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003892 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3894 final long ident = Binder.clearCallingIdentity();
3895 try {
3896 synchronized (mGlobalLock) {
3897 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003898 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003899 if (stack == null) {
3900 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3901 return;
3902 }
3903
3904 if (toTop) {
3905 // Caller wants the current split-screen primary stack to be the top stack after
3906 // it goes fullscreen, so move it to the front.
3907 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003908 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003910 // stack after it goes fullscreen, so we move the focus to the top-most
3911 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3913 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3914 if (otherStack != null) {
3915 otherStack.moveToFront("dismissSplitScreenMode_other");
3916 }
3917 }
3918
Evan Rosky10475742018-09-05 19:02:48 -07003919 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003920 }
3921 } finally {
3922 Binder.restoreCallingIdentity(ident);
3923 }
3924 }
3925
3926 /**
3927 * Dismisses Pip
3928 * @param animate True if the dismissal should be animated.
3929 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3930 * default animation duration should be used.
3931 */
3932 @Override
3933 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003934 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 final long ident = Binder.clearCallingIdentity();
3936 try {
3937 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003938 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003939 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 if (stack == null) {
3941 Slog.w(TAG, "dismissPip: pinned stack not found.");
3942 return;
3943 }
3944 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3945 throw new IllegalArgumentException("Stack: " + stack
3946 + " doesn't support animated resize.");
3947 }
3948 if (animate) {
3949 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3950 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3951 } else {
3952 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3953 }
3954 }
3955 } finally {
3956 Binder.restoreCallingIdentity(ident);
3957 }
3958 }
3959
3960 @Override
3961 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003962 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 synchronized (mGlobalLock) {
3964 mSuppressResizeConfigChanges = suppress;
3965 }
3966 }
3967
3968 /**
3969 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3970 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3971 * activity and clearing the task at the same time.
3972 */
3973 @Override
3974 // TODO: API should just be about changing windowing modes...
3975 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003976 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 "moveTasksToFullscreenStack()");
3978 synchronized (mGlobalLock) {
3979 final long origId = Binder.clearCallingIdentity();
3980 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003981 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003982 if (stack != null){
3983 if (!stack.isActivityTypeStandardOrUndefined()) {
3984 throw new IllegalArgumentException(
3985 "You can't move tasks from non-standard stacks.");
3986 }
3987 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3988 }
3989 } finally {
3990 Binder.restoreCallingIdentity(origId);
3991 }
3992 }
3993 }
3994
3995 /**
3996 * Moves the top activity in the input stackId to the pinned stack.
3997 *
3998 * @param stackId Id of stack to move the top activity to pinned stack.
3999 * @param bounds Bounds to use for pinned stack.
4000 *
4001 * @return True if the top activity of the input stack was successfully moved to the pinned
4002 * stack.
4003 */
4004 @Override
4005 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004006 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 "moveTopActivityToPinnedStack()");
4008 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004009 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004010 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4011 + "Device doesn't support picture-in-picture mode");
4012 }
4013
4014 long ident = Binder.clearCallingIdentity();
4015 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004016 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004017 } finally {
4018 Binder.restoreCallingIdentity(ident);
4019 }
4020 }
4021 }
4022
4023 @Override
4024 public boolean isInMultiWindowMode(IBinder token) {
4025 final long origId = Binder.clearCallingIdentity();
4026 try {
4027 synchronized (mGlobalLock) {
4028 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4029 if (r == null) {
4030 return false;
4031 }
4032 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4033 return r.inMultiWindowMode();
4034 }
4035 } finally {
4036 Binder.restoreCallingIdentity(origId);
4037 }
4038 }
4039
4040 @Override
4041 public boolean isInPictureInPictureMode(IBinder token) {
4042 final long origId = Binder.clearCallingIdentity();
4043 try {
4044 synchronized (mGlobalLock) {
4045 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4046 }
4047 } finally {
4048 Binder.restoreCallingIdentity(origId);
4049 }
4050 }
4051
4052 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004053 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4054 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004055 return false;
4056 }
4057
4058 // If we are animating to fullscreen then we have already dispatched the PIP mode
4059 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004060 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4061 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004062 }
4063
4064 @Override
4065 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4066 final long origId = Binder.clearCallingIdentity();
4067 try {
4068 synchronized (mGlobalLock) {
4069 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4070 "enterPictureInPictureMode", token, params);
4071
4072 // If the activity is already in picture in picture mode, then just return early
4073 if (isInPictureInPictureMode(r)) {
4074 return true;
4075 }
4076
4077 // Activity supports picture-in-picture, now check that we can enter PiP at this
4078 // point, if it is
4079 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4080 false /* beforeStopping */)) {
4081 return false;
4082 }
4083
4084 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004085 synchronized (mGlobalLock) {
4086 // Only update the saved args from the args that are set
4087 r.pictureInPictureArgs.copyOnlySet(params);
4088 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4089 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4090 // Adjust the source bounds by the insets for the transition down
4091 final Rect sourceBounds = new Rect(
4092 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004093 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004094 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004095 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004096 stack.setPictureInPictureAspectRatio(aspectRatio);
4097 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004098 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4099 r.info.applicationInfo.uid, r.shortComponentName,
4100 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004101 logPictureInPictureArgs(params);
4102 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 };
4104
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004105 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004106 // If the keyguard is showing or occluded, then try and dismiss it before
4107 // entering picture-in-picture (this will prompt the user to authenticate if the
4108 // device is currently locked).
4109 dismissKeyguard(token, new KeyguardDismissCallback() {
4110 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004111 public void onDismissSucceeded() {
4112 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 }
4114 }, null /* message */);
4115 } else {
4116 // Enter picture in picture immediately otherwise
4117 enterPipRunnable.run();
4118 }
4119 return true;
4120 }
4121 } finally {
4122 Binder.restoreCallingIdentity(origId);
4123 }
4124 }
4125
4126 @Override
4127 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4128 final long origId = Binder.clearCallingIdentity();
4129 try {
4130 synchronized (mGlobalLock) {
4131 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4132 "setPictureInPictureParams", token, params);
4133
4134 // Only update the saved args from the args that are set
4135 r.pictureInPictureArgs.copyOnlySet(params);
4136 if (r.inPinnedWindowingMode()) {
4137 // If the activity is already in picture-in-picture, update the pinned stack now
4138 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4139 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004140 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004141 if (!stack.isAnimatingBoundsToFullscreen()) {
4142 stack.setPictureInPictureAspectRatio(
4143 r.pictureInPictureArgs.getAspectRatio());
4144 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4145 }
4146 }
4147 logPictureInPictureArgs(params);
4148 }
4149 } finally {
4150 Binder.restoreCallingIdentity(origId);
4151 }
4152 }
4153
4154 @Override
4155 public int getMaxNumPictureInPictureActions(IBinder token) {
4156 // Currently, this is a static constant, but later, we may change this to be dependent on
4157 // the context of the activity
4158 return 3;
4159 }
4160
4161 private void logPictureInPictureArgs(PictureInPictureParams params) {
4162 if (params.hasSetActions()) {
4163 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4164 params.getActions().size());
4165 }
4166 if (params.hasSetAspectRatio()) {
4167 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4168 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4169 MetricsLogger.action(lm);
4170 }
4171 }
4172
4173 /**
4174 * Checks the state of the system and the activity associated with the given {@param token} to
4175 * verify that picture-in-picture is supported for that activity.
4176 *
4177 * @return the activity record for the given {@param token} if all the checks pass.
4178 */
4179 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4180 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004181 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 throw new IllegalStateException(caller
4183 + ": Device doesn't support picture-in-picture mode.");
4184 }
4185
4186 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4187 if (r == null) {
4188 throw new IllegalStateException(caller
4189 + ": Can't find activity for token=" + token);
4190 }
4191
4192 if (!r.supportsPictureInPicture()) {
4193 throw new IllegalStateException(caller
4194 + ": Current activity does not support picture-in-picture.");
4195 }
4196
4197 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004198 && !mWindowManager.isValidPictureInPictureAspectRatio(
4199 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 final float minAspectRatio = mContext.getResources().getFloat(
4201 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4202 final float maxAspectRatio = mContext.getResources().getFloat(
4203 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4204 throw new IllegalArgumentException(String.format(caller
4205 + ": Aspect ratio is too extreme (must be between %f and %f).",
4206 minAspectRatio, maxAspectRatio));
4207 }
4208
4209 // Truncate the number of actions if necessary
4210 params.truncateActions(getMaxNumPictureInPictureActions(token));
4211
4212 return r;
4213 }
4214
4215 @Override
4216 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 synchronized (mGlobalLock) {
4219 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4220 if (r == null) {
4221 throw new IllegalArgumentException("Activity does not exist; token="
4222 + activityToken);
4223 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004224 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 }
4226 }
4227
4228 @Override
4229 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4230 Rect tempDockedTaskInsetBounds,
4231 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004232 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 long ident = Binder.clearCallingIdentity();
4234 try {
4235 synchronized (mGlobalLock) {
4236 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4237 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4238 PRESERVE_WINDOWS);
4239 }
4240 } finally {
4241 Binder.restoreCallingIdentity(ident);
4242 }
4243 }
4244
4245 @Override
4246 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004248 final long ident = Binder.clearCallingIdentity();
4249 try {
4250 synchronized (mGlobalLock) {
4251 mStackSupervisor.setSplitScreenResizing(resizing);
4252 }
4253 } finally {
4254 Binder.restoreCallingIdentity(ident);
4255 }
4256 }
4257
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 /**
4259 * Check that we have the features required for VR-related API calls, and throw an exception if
4260 * not.
4261 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004262 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004263 if (!mContext.getPackageManager().hasSystemFeature(
4264 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4265 throw new UnsupportedOperationException("VR mode not supported on this device!");
4266 }
4267 }
4268
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 @Override
4270 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004272
4273 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4274
4275 ActivityRecord r;
4276 synchronized (mGlobalLock) {
4277 r = ActivityRecord.isInStackLocked(token);
4278 }
4279
4280 if (r == null) {
4281 throw new IllegalArgumentException();
4282 }
4283
4284 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004285 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 VrManagerInternal.NO_ERROR) {
4287 return err;
4288 }
4289
4290 // Clear the binder calling uid since this path may call moveToTask().
4291 final long callingId = Binder.clearCallingIdentity();
4292 try {
4293 synchronized (mGlobalLock) {
4294 r.requestedVrComponent = (enabled) ? packageName : null;
4295
4296 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004297 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004298 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
4300 return 0;
4301 }
4302 } finally {
4303 Binder.restoreCallingIdentity(callingId);
4304 }
4305 }
4306
4307 @Override
4308 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4309 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4310 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004311 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4313 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4314 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004315 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 || activity.voiceSession != null) {
4317 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4318 return;
4319 }
4320 if (activity.pendingVoiceInteractionStart) {
4321 Slog.w(TAG, "Pending start of voice interaction already.");
4322 return;
4323 }
4324 activity.pendingVoiceInteractionStart = true;
4325 }
4326 LocalServices.getService(VoiceInteractionManagerInternal.class)
4327 .startLocalVoiceInteraction(callingActivity, options);
4328 }
4329
4330 @Override
4331 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4332 LocalServices.getService(VoiceInteractionManagerInternal.class)
4333 .stopLocalVoiceInteraction(callingActivity);
4334 }
4335
4336 @Override
4337 public boolean supportsLocalVoiceInteraction() {
4338 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4339 .supportsLocalVoiceInteraction();
4340 }
4341
4342 /** Notifies all listeners when the pinned stack animation starts. */
4343 @Override
4344 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004345 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004346 }
4347
4348 /** Notifies all listeners when the pinned stack animation ends. */
4349 @Override
4350 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004351 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 }
4353
4354 @Override
4355 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004356 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004357 final long ident = Binder.clearCallingIdentity();
4358 try {
4359 synchronized (mGlobalLock) {
4360 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4361 }
4362 } finally {
4363 Binder.restoreCallingIdentity(ident);
4364 }
4365 }
4366
4367 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004369 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370
4371 synchronized (mGlobalLock) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08004372 if (mWindowManager == null) {
4373 Slog.w(TAG, "Skip updateConfiguration because mWindowManager isn't set");
4374 return false;
4375 }
4376
4377 if (values == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 }
4381
Riddle Hsua0022cd2019-09-09 21:12:41 +08004382 mH.sendMessage(PooledLambda.obtainMessage(
4383 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4384 DEFAULT_DISPLAY));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385
4386 final long origId = Binder.clearCallingIdentity();
4387 try {
4388 if (values != null) {
4389 Settings.System.clearConfiguration(values);
4390 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 UserHandle.USER_NULL, false /* deferResume */,
4393 mTmpUpdateConfigurationResult);
4394 return mTmpUpdateConfigurationResult.changes != 0;
4395 } finally {
4396 Binder.restoreCallingIdentity(origId);
4397 }
4398 }
4399 }
4400
4401 @Override
4402 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4403 CharSequence message) {
4404 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004405 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4407 }
4408 final long callingId = Binder.clearCallingIdentity();
4409 try {
4410 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004411 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 }
4413 } finally {
4414 Binder.restoreCallingIdentity(callingId);
4415 }
4416 }
4417
4418 @Override
4419 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004420 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 "cancelTaskWindowTransition()");
4422 final long ident = Binder.clearCallingIdentity();
4423 try {
4424 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004425 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 MATCH_TASK_IN_STACKS_ONLY);
4427 if (task == null) {
4428 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4429 return;
4430 }
4431 task.cancelWindowTransition();
4432 }
4433 } finally {
4434 Binder.restoreCallingIdentity(ident);
4435 }
4436 }
4437
4438 @Override
4439 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004440 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 final long ident = Binder.clearCallingIdentity();
4442 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004443 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 } finally {
4445 Binder.restoreCallingIdentity(ident);
4446 }
4447 }
4448
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004449 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4450 boolean restoreFromDisk) {
4451 final TaskRecord task;
4452 synchronized (mGlobalLock) {
4453 task = mRootActivityContainer.anyTaskForId(taskId,
4454 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4455 if (task == null) {
4456 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4457 return null;
4458 }
4459 }
4460 // Don't call this while holding the lock as this operation might hit the disk.
4461 return task.getSnapshot(reducedResolution, restoreFromDisk);
4462 }
4463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004464 @Override
4465 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4466 synchronized (mGlobalLock) {
4467 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4468 if (r == null) {
4469 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4470 + token);
4471 return;
4472 }
4473 final long origId = Binder.clearCallingIdentity();
4474 try {
4475 r.setDisablePreviewScreenshots(disable);
4476 } finally {
4477 Binder.restoreCallingIdentity(origId);
4478 }
4479 }
4480 }
4481
4482 /** Return the user id of the last resumed activity. */
4483 @Override
4484 public @UserIdInt
4485 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004486 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4488 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004489 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004490 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004491 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004492 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 }
4494 }
4495
4496 @Override
4497 public void updateLockTaskFeatures(int userId, int flags) {
4498 final int callingUid = Binder.getCallingUid();
4499 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 "updateLockTaskFeatures()");
4502 }
4503 synchronized (mGlobalLock) {
4504 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4505 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004506 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 }
4508 }
4509
4510 @Override
4511 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4512 synchronized (mGlobalLock) {
4513 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4514 if (r == null) {
4515 return;
4516 }
4517 final long origId = Binder.clearCallingIdentity();
4518 try {
4519 r.setShowWhenLocked(showWhenLocked);
4520 } finally {
4521 Binder.restoreCallingIdentity(origId);
4522 }
4523 }
4524 }
4525
4526 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004527 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4528 synchronized (mGlobalLock) {
4529 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4530 if (r == null) {
4531 return;
4532 }
4533 final long origId = Binder.clearCallingIdentity();
4534 try {
4535 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4536 } finally {
4537 Binder.restoreCallingIdentity(origId);
4538 }
4539 }
4540 }
4541
4542 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4544 synchronized (mGlobalLock) {
4545 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4546 if (r == null) {
4547 return;
4548 }
4549 final long origId = Binder.clearCallingIdentity();
4550 try {
4551 r.setTurnScreenOn(turnScreenOn);
4552 } finally {
4553 Binder.restoreCallingIdentity(origId);
4554 }
4555 }
4556 }
4557
4558 @Override
4559 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004561 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004562 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004563 synchronized (mGlobalLock) {
4564 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4565 if (r == null) {
4566 return;
4567 }
4568 final long origId = Binder.clearCallingIdentity();
4569 try {
4570 r.registerRemoteAnimations(definition);
4571 } finally {
4572 Binder.restoreCallingIdentity(origId);
4573 }
4574 }
4575 }
4576
4577 @Override
4578 public void registerRemoteAnimationForNextActivityStart(String packageName,
4579 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004580 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004581 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004582 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 synchronized (mGlobalLock) {
4584 final long origId = Binder.clearCallingIdentity();
4585 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004586 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 packageName, adapter);
4588 } finally {
4589 Binder.restoreCallingIdentity(origId);
4590 }
4591 }
4592 }
4593
Evan Rosky966759f2019-01-15 10:33:58 -08004594 @Override
4595 public void registerRemoteAnimationsForDisplay(int displayId,
4596 RemoteAnimationDefinition definition) {
4597 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4598 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004599 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004600 synchronized (mGlobalLock) {
4601 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4602 if (display == null) {
4603 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4604 return;
4605 }
4606 final long origId = Binder.clearCallingIdentity();
4607 try {
4608 display.mDisplayContent.registerRemoteAnimations(definition);
4609 } finally {
4610 Binder.restoreCallingIdentity(origId);
4611 }
4612 }
4613 }
4614
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004615 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4616 @Override
4617 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4618 synchronized (mGlobalLock) {
4619 final long origId = Binder.clearCallingIdentity();
4620 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004621 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004622 } finally {
4623 Binder.restoreCallingIdentity(origId);
4624 }
4625 }
4626 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004627
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004628 @Override
4629 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004630 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004631 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004632 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004633 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004634 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004635 }
4636 }
4637
4638 @Override
4639 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 != PERMISSION_GRANTED) {
4642 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4643 + Binder.getCallingPid()
4644 + ", uid=" + Binder.getCallingUid()
4645 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4646 Slog.w(TAG, msg);
4647 throw new SecurityException(msg);
4648 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004649 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004651 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004652 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004653 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004654 }
4655 }
4656
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004657 @Override
4658 public void stopAppSwitches() {
4659 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4660 synchronized (mGlobalLock) {
4661 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004662 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004663 mDidAppSwitch = false;
4664 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4665 }
4666 }
4667
4668 @Override
4669 public void resumeAppSwitches() {
4670 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4671 synchronized (mGlobalLock) {
4672 // Note that we don't execute any pending app switches... we will
4673 // let those wait until either the timeout, or the next start
4674 // activity request.
4675 mAppSwitchesAllowedTime = 0;
4676 }
4677 }
4678
Ricky Wai906af482019-06-03 17:25:28 +01004679 long getLastStopAppSwitchesTime() {
4680 return mLastStopAppSwitchesTime;
4681 }
4682
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004683 void onStartActivitySetDidAppSwitch() {
4684 if (mDidAppSwitch) {
4685 // This is the second allowed switch since we stopped switches, so now just generally
4686 // allow switches. Use case:
4687 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4688 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4689 // anyone to switch again).
4690 mAppSwitchesAllowedTime = 0;
4691 } else {
4692 mDidAppSwitch = true;
4693 }
4694 }
4695
4696 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004697 boolean shouldDisableNonVrUiLocked() {
4698 return mVrController.shouldDisableNonVrUiLocked();
4699 }
4700
Wale Ogunwale53783742018-09-16 10:21:51 -07004701 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 // 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 +00004703 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004704 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004705 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4706 + " to main display for VR");
4707 mRootActivityContainer.moveStackToDisplay(
4708 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004709 }
4710 mH.post(() -> {
4711 if (!mVrController.onVrModeChanged(r)) {
4712 return;
4713 }
4714 synchronized (mGlobalLock) {
4715 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4716 mWindowManager.disableNonVrUi(disableNonVrUi);
4717 if (disableNonVrUi) {
4718 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4719 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004720 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 }
4722 }
4723 });
4724 }
4725
Wale Ogunwale53783742018-09-16 10:21:51 -07004726 @Override
4727 public int getPackageScreenCompatMode(String packageName) {
4728 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4729 synchronized (mGlobalLock) {
4730 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4731 }
4732 }
4733
4734 @Override
4735 public void setPackageScreenCompatMode(String packageName, int mode) {
4736 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4737 "setPackageScreenCompatMode");
4738 synchronized (mGlobalLock) {
4739 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4740 }
4741 }
4742
4743 @Override
4744 public boolean getPackageAskScreenCompat(String packageName) {
4745 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4746 synchronized (mGlobalLock) {
4747 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4748 }
4749 }
4750
4751 @Override
4752 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4753 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4754 "setPackageAskScreenCompat");
4755 synchronized (mGlobalLock) {
4756 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4757 }
4758 }
4759
Wale Ogunwale64258362018-10-16 15:13:37 -07004760 public static String relaunchReasonToString(int relaunchReason) {
4761 switch (relaunchReason) {
4762 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4763 return "window_resize";
4764 case RELAUNCH_REASON_FREE_RESIZE:
4765 return "free_resize";
4766 default:
4767 return null;
4768 }
4769 }
4770
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004771 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004772 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004773 }
4774
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004775 /** Pokes the task persister. */
4776 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4777 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4778 }
4779
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004780 boolean isKeyguardLocked() {
4781 return mKeyguardController.isKeyguardLocked();
4782 }
4783
Garfield Tan01548632018-11-27 10:15:48 -08004784 /**
4785 * Clears launch params for the given package.
4786 * @param packageNames the names of the packages of which the launch params are to be cleared
4787 */
4788 @Override
4789 public void clearLaunchParamsForPackages(List<String> packageNames) {
4790 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4791 "clearLaunchParamsForPackages");
4792 synchronized (mGlobalLock) {
4793 for (int i = 0; i < packageNames.size(); ++i) {
4794 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4795 }
4796 }
4797 }
4798
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004799 /**
4800 * Makes the display with the given id a single task instance display. I.e the display can only
4801 * contain one task.
4802 */
4803 @Override
4804 public void setDisplayToSingleTaskInstance(int displayId) {
4805 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4806 "setDisplayToSingleTaskInstance");
4807 final long origId = Binder.clearCallingIdentity();
4808 try {
4809 final ActivityDisplay display =
4810 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4811 if (display != null) {
4812 display.setDisplayToSingleTaskInstance();
4813 }
4814 } finally {
4815 Binder.restoreCallingIdentity(origId);
4816 }
4817 }
4818
Wale Ogunwale31913b52018-10-13 08:29:31 -07004819 void dumpLastANRLocked(PrintWriter pw) {
4820 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4821 if (mLastANRState == null) {
4822 pw.println(" <no ANR has occurred since boot>");
4823 } else {
4824 pw.println(mLastANRState);
4825 }
4826 }
4827
4828 void dumpLastANRTracesLocked(PrintWriter pw) {
4829 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4830
4831 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4832 if (ArrayUtils.isEmpty(files)) {
4833 pw.println(" <no ANR has occurred since boot>");
4834 return;
4835 }
4836 // Find the latest file.
4837 File latest = null;
4838 for (File f : files) {
4839 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4840 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004841 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004842 }
4843 pw.print("File: ");
4844 pw.print(latest.getName());
4845 pw.println();
4846 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4847 String line;
4848 while ((line = in.readLine()) != null) {
4849 pw.println(line);
4850 }
4851 } catch (IOException e) {
4852 pw.print("Unable to read: ");
4853 pw.print(e);
4854 pw.println();
4855 }
4856 }
4857
4858 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4859 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4860 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4861 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4862 }
4863
4864 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4865 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4866 pw.println(header);
4867
Wale Ogunwaled32da472018-11-16 07:19:28 -08004868 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004869 dumpPackage);
4870 boolean needSep = printedAnything;
4871
4872 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004873 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004874 " ResumedActivity: ");
4875 if (printed) {
4876 printedAnything = true;
4877 needSep = false;
4878 }
4879
4880 if (dumpPackage == null) {
4881 if (needSep) {
4882 pw.println();
4883 }
4884 printedAnything = true;
4885 mStackSupervisor.dump(pw, " ");
4886 }
4887
4888 if (!printedAnything) {
4889 pw.println(" (nothing)");
4890 }
4891 }
4892
4893 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004894 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004895 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004896 pw.println(" ");
4897 }
4898
4899 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4900 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4901 getActivityStartController().dump(pw, "", dumpPackage);
4902 }
4903
4904 /**
4905 * There are three things that cmd can be:
4906 * - a flattened component name that matches an existing activity
4907 * - the cmd arg isn't the flattened component name of an existing activity:
4908 * dump all activity whose component contains the cmd as a substring
4909 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004910 * <p>
4911 * The caller should not hold lock when calling this method because it will wait for the
4912 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004913 *
4914 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4915 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4916 */
4917 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4918 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4919 ArrayList<ActivityRecord> activities;
4920
4921 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004922 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004923 dumpFocusedStackOnly);
4924 }
4925
4926 if (activities.size() <= 0) {
4927 return false;
4928 }
4929
4930 String[] newArgs = new String[args.length - opti];
4931 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4932
4933 TaskRecord lastTask = null;
4934 boolean needSep = false;
4935 for (int i = activities.size() - 1; i >= 0; i--) {
4936 ActivityRecord r = activities.get(i);
4937 if (needSep) {
4938 pw.println();
4939 }
4940 needSep = true;
4941 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004942 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004943 if (lastTask != task) {
4944 lastTask = task;
4945 pw.print("TASK "); pw.print(lastTask.affinity);
Wale Ogunwale4e79a1c2019-10-05 20:52:40 -07004946 pw.print(" id="); pw.print(lastTask.mTaskId);
4947 pw.print(" userId="); pw.println(lastTask.mUserId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004948 if (dumpAll) {
4949 lastTask.dump(pw, " ");
4950 }
4951 }
4952 }
4953 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4954 }
4955 return true;
4956 }
4957
4958 /**
4959 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4960 * there is a thread associated with the activity.
4961 */
4962 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4963 final ActivityRecord r, String[] args, boolean dumpAll) {
4964 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004965 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004966 synchronized (mGlobalLock) {
4967 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4968 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4969 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004970 if (r.hasProcess()) {
4971 pw.println(r.app.getPid());
4972 appThread = r.app.getThread();
4973 } else {
4974 pw.println("(not running)");
4975 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004976 if (dumpAll) {
4977 r.dump(pw, innerPrefix);
4978 }
4979 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004980 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004981 // flush anything that is already in the PrintWriter since the thread is going
4982 // to write to the file descriptor directly
4983 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004984 try (TransferPipe tp = new TransferPipe()) {
4985 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4986 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004987 } catch (IOException e) {
4988 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4989 } catch (RemoteException e) {
4990 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4991 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004992 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004993 }
4994
sanryhuang498e77e2018-12-06 14:57:01 +08004995 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4996 boolean testPssMode) {
4997 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4998 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4999 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005000 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5002 st.toString());
5003 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005004 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5005 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5006 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005007 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5008 testPssMode);
5009 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005010 }
5011
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005012 int getCurrentUserId() {
5013 return mAmInternal.getCurrentUserId();
5014 }
5015
5016 private void enforceNotIsolatedCaller(String caller) {
5017 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5018 throw new SecurityException("Isolated process not allowed to call " + caller);
5019 }
5020 }
5021
Wale Ogunwalef6733932018-06-27 05:14:34 -07005022 public Configuration getConfiguration() {
5023 Configuration ci;
5024 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005025 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005026 ci.userSetLocale = false;
5027 }
5028 return ci;
5029 }
5030
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005031 /**
5032 * Current global configuration information. Contains general settings for the entire system,
5033 * also corresponds to the merged configuration of the default display.
5034 */
5035 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005036 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005037 }
5038
5039 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5040 boolean initLocale) {
5041 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5042 }
5043
5044 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5045 boolean initLocale, boolean deferResume) {
5046 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5047 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5048 UserHandle.USER_NULL, deferResume);
5049 }
5050
Wale Ogunwale59507092018-10-29 09:00:30 -07005051 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005052 final long origId = Binder.clearCallingIdentity();
5053 try {
5054 synchronized (mGlobalLock) {
5055 updateConfigurationLocked(values, null, false, true, userId,
5056 false /* deferResume */);
5057 }
5058 } finally {
5059 Binder.restoreCallingIdentity(origId);
5060 }
5061 }
5062
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005063 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5064 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5065 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5066 deferResume, null /* result */);
5067 }
5068
5069 /**
5070 * Do either or both things: (1) change the current configuration, and (2)
5071 * make sure the given activity is running with the (now) current
5072 * configuration. Returns true if the activity has been left running, or
5073 * false if <var>starting</var> is being destroyed to match the new
5074 * configuration.
5075 *
5076 * @param userId is only used when persistent parameter is set to true to persist configuration
5077 * for that particular user
5078 */
5079 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5080 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5081 ActivityTaskManagerService.UpdateConfigurationResult result) {
5082 int changes = 0;
5083 boolean kept = true;
5084
Riddle Hsua0022cd2019-09-09 21:12:41 +08005085 deferWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086 try {
5087 if (values != null) {
5088 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5089 deferResume);
5090 }
5091
5092 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5093 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08005094 continueWindowLayout();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005095 }
5096
5097 if (result != null) {
5098 result.changes = changes;
5099 result.activityRelaunched = !kept;
5100 }
5101 return kept;
5102 }
5103
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005104 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005105 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005106 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005107
5108 final ActivityDisplay defaultDisplay =
5109 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5110
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005111 mTempConfig.setTo(getGlobalConfiguration());
5112 final int changes = mTempConfig.updateFrom(values);
5113 if (changes == 0) {
5114 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5115 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5116 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5117 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005118 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005119 return 0;
5120 }
5121
5122 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5123 "Updating global configuration to: " + values);
5124
5125 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5126 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5127 values.colorMode,
5128 values.densityDpi,
5129 values.fontScale,
5130 values.hardKeyboardHidden,
5131 values.keyboard,
5132 values.keyboardHidden,
5133 values.mcc,
5134 values.mnc,
5135 values.navigation,
5136 values.navigationHidden,
5137 values.orientation,
5138 values.screenHeightDp,
5139 values.screenLayout,
5140 values.screenWidthDp,
5141 values.smallestScreenWidthDp,
5142 values.touchscreen,
5143 values.uiMode);
5144
5145
5146 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5147 final LocaleList locales = values.getLocales();
5148 int bestLocaleIndex = 0;
5149 if (locales.size() > 1) {
5150 if (mSupportedSystemLocales == null) {
5151 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5152 }
5153 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5154 }
5155 SystemProperties.set("persist.sys.locale",
5156 locales.get(bestLocaleIndex).toLanguageTag());
5157 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005158
5159 final Message m = PooledLambda.obtainMessage(
5160 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5161 locales.get(bestLocaleIndex));
5162 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005163 }
5164
Yunfan Chen75157d72018-07-27 14:47:21 +09005165 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005166
5167 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005168 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005169
5170 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5171 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005172 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005173
5174 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005175 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005176
5177 AttributeCache ac = AttributeCache.instance();
5178 if (ac != null) {
5179 ac.updateConfiguration(mTempConfig);
5180 }
5181
5182 // Make sure all resources in our process are updated right now, so that anyone who is going
5183 // to retrieve resource values after we return will be sure to get the new ones. This is
5184 // especially important during boot, where the first config change needs to guarantee all
5185 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005186 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 // We need another copy of global config because we're scheduling some calls instead of
5189 // running them in place. We need to be sure that object we send will be handled unchanged.
5190 final Configuration configCopy = new Configuration(mTempConfig);
5191 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005192 final Message msg = PooledLambda.obtainMessage(
5193 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5194 this, userId, configCopy);
5195 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196 }
5197
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005198 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5199 for (int i = pidMap.size() - 1; i >= 0; i--) {
5200 final int pid = pidMap.keyAt(i);
5201 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005202 if (DEBUG_CONFIGURATION) {
5203 Slog.v(TAG_CONFIGURATION, "Update process config of "
5204 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005206 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005207 }
5208
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005209 final Message msg = PooledLambda.obtainMessage(
5210 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5211 mAmInternal, changes, initLocale);
5212 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005213
5214 // Override configuration of the default display duplicates global config, so we need to
5215 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005216 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5217 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218
5219 return changes;
5220 }
5221
Riddle Hsua0022cd2019-09-09 21:12:41 +08005222 /** @see WindowSurfacePlacer#deferLayout */
5223 void deferWindowLayout() {
5224 if (!mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5225 // Reset the reasons at the first entrance because we only care about the changes in the
5226 // deferred scope.
5227 mLayoutReasons = 0;
5228 }
5229
5230 mWindowManager.mWindowPlacerLocked.deferLayout();
5231 }
5232
5233 /** @see WindowSurfacePlacer#continueLayout */
5234 void continueWindowLayout() {
5235 mWindowManager.mWindowPlacerLocked.continueLayout(mLayoutReasons != 0);
5236 if (DEBUG_ALL && !mWindowManager.mWindowPlacerLocked.isLayoutDeferred()) {
5237 Slog.i(TAG, "continueWindowLayout reason=" + mLayoutReasons);
5238 }
5239 }
5240
5241 /**
5242 * If a reason is added between {@link #deferWindowLayout} and {@link #continueWindowLayout},
5243 * it will make sure {@link WindowSurfacePlacer#performSurfacePlacement} is called when the last
5244 * defer count is gone.
5245 */
5246 void addWindowLayoutReasons(@LayoutReason int reasons) {
5247 mLayoutReasons |= reasons;
5248 }
5249
Wale Ogunwalef6733932018-06-27 05:14:34 -07005250 private void updateEventDispatchingLocked(boolean booted) {
5251 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5252 }
5253
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005254 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5255 final ContentResolver resolver = mContext.getContentResolver();
5256 Settings.System.putConfigurationForUser(resolver, config, userId);
5257 }
5258
5259 private void sendLocaleToMountDaemonMsg(Locale l) {
5260 try {
5261 IBinder service = ServiceManager.getService("mount");
5262 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5263 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5264 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5265 } catch (RemoteException e) {
5266 Log.e(TAG, "Error storing locale for decryption UI", e);
5267 }
5268 }
5269
Alison Cichowlas3e340502018-08-07 17:15:01 -04005270 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5271 mStartActivitySources.remove(permissionToken);
5272 mExpiredStartAsCallerTokens.add(permissionToken);
5273 }
5274
5275 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5276 mExpiredStartAsCallerTokens.remove(permissionToken);
5277 }
5278
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005279 boolean isActivityStartsLoggingEnabled() {
5280 return mAmInternal.isActivityStartsLoggingEnabled();
5281 }
5282
Michal Karpinski8596ded2018-11-14 14:43:48 +00005283 boolean isBackgroundActivityStartsEnabled() {
5284 return mAmInternal.isBackgroundActivityStartsEnabled();
5285 }
5286
Wale Ogunwalef6733932018-06-27 05:14:34 -07005287 void enableScreenAfterBoot(boolean booted) {
5288 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5289 SystemClock.uptimeMillis());
5290 mWindowManager.enableScreenAfterBoot();
5291
5292 synchronized (mGlobalLock) {
5293 updateEventDispatchingLocked(booted);
5294 }
5295 }
5296
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005297 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5298 if (r == null || !r.hasProcess()) {
5299 return KEY_DISPATCHING_TIMEOUT_MS;
5300 }
5301 return getInputDispatchingTimeoutLocked(r.app);
5302 }
5303
5304 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005305 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005306 }
5307
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 /**
5309 * Decide based on the configuration whether we should show the ANR,
5310 * crash, etc dialogs. The idea is that if there is no affordance to
5311 * press the on-screen buttons, or the user experience would be more
5312 * greatly impacted than the crash itself, we shouldn't show the dialog.
5313 *
5314 * A thought: SystemUI might also want to get told about this, the Power
5315 * dialog / global actions also might want different behaviors.
5316 */
5317 private void updateShouldShowDialogsLocked(Configuration config) {
5318 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5319 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5320 && config.navigation == Configuration.NAVIGATION_NONAV);
5321 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5322 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5323 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5324 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5325 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5326 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5327 HIDE_ERROR_DIALOGS, 0) != 0;
5328 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5329 }
5330
5331 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5332 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5333 FONT_SCALE, 1.0f, userId);
5334
Riddle Hsu8419e4b2019-09-18 23:28:01 +08005335 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005336 if (getGlobalConfiguration().fontScale == scaleFactor) {
5337 return;
5338 }
5339
5340 final Configuration configuration
5341 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5342 configuration.fontScale = scaleFactor;
5343 updatePersistentConfiguration(configuration, userId);
5344 }
5345 }
5346
5347 // Actually is sleeping or shutting down or whatever else in the future
5348 // is an inactive state.
5349 boolean isSleepingOrShuttingDownLocked() {
5350 return isSleepingLocked() || mShuttingDown;
5351 }
5352
5353 boolean isSleepingLocked() {
5354 return mSleeping;
5355 }
5356
Riddle Hsu16567132018-08-16 21:37:47 +08005357 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005359 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 if (task.isActivityTypeStandard()) {
5361 if (mCurAppTimeTracker != r.appTimeTracker) {
5362 // We are switching app tracking. Complete the current one.
5363 if (mCurAppTimeTracker != null) {
5364 mCurAppTimeTracker.stop();
5365 mH.obtainMessage(
5366 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005367 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005368 mCurAppTimeTracker = null;
5369 }
5370 if (r.appTimeTracker != null) {
5371 mCurAppTimeTracker = r.appTimeTracker;
5372 startTimeTrackingFocusedActivityLocked();
5373 }
5374 } else {
5375 startTimeTrackingFocusedActivityLocked();
5376 }
5377 } else {
5378 r.appTimeTracker = null;
5379 }
5380 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5381 // TODO: Probably not, because we don't want to resume voice on switching
5382 // back to this activity
5383 if (task.voiceInteractor != null) {
5384 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5385 } else {
5386 finishRunningVoiceLocked();
5387
5388 if (mLastResumedActivity != null) {
5389 final IVoiceInteractionSession session;
5390
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005391 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 if (lastResumedActivityTask != null
5393 && lastResumedActivityTask.voiceSession != null) {
5394 session = lastResumedActivityTask.voiceSession;
5395 } else {
5396 session = mLastResumedActivity.voiceSession;
5397 }
5398
5399 if (session != null) {
5400 // We had been in a voice interaction session, but now focused has
5401 // move to something different. Just finish the session, we can't
5402 // return to it and retain the proper state and synchronization with
5403 // the voice interaction service.
5404 finishVoiceTask(session);
5405 }
5406 }
5407 }
5408
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005409 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5410 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 }
5412 updateResumedAppTrace(r);
5413 mLastResumedActivity = r;
5414
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005415 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416
5417 applyUpdateLockStateLocked(r);
5418 applyUpdateVrModeLocked(r);
5419
5420 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005421 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 r == null ? "NULL" : r.shortComponentName,
5423 reason);
5424 }
5425
5426 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5427 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005428 final ActivityTaskManagerInternal.SleepToken token =
5429 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005430 updateSleepIfNeededLocked();
5431 return token;
5432 }
5433 }
5434
5435 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005436 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 final boolean wasSleeping = mSleeping;
5438 boolean updateOomAdj = false;
5439
5440 if (!shouldSleep) {
5441 // If wasSleeping is true, we need to wake up activity manager state from when
5442 // we started sleeping. In either case, we need to apply the sleep tokens, which
5443 // will wake up stacks or put them to sleep as appropriate.
5444 if (wasSleeping) {
5445 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005446 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5447 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 startTimeTrackingFocusedActivityLocked();
5449 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005450 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5452 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005453 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 if (wasSleeping) {
5455 updateOomAdj = true;
5456 }
5457 } else if (!mSleeping && shouldSleep) {
5458 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005459 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5460 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 if (mCurAppTimeTracker != null) {
5462 mCurAppTimeTracker.stop();
5463 }
5464 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005465 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 mStackSupervisor.goingToSleepLocked();
5467 updateResumedAppTrace(null /* resumed */);
5468 updateOomAdj = true;
5469 }
5470 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005471 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 }
5473 }
5474
5475 void updateOomAdj() {
5476 mH.post(mAmInternal::updateOomAdj);
5477 }
5478
Wale Ogunwale53783742018-09-16 10:21:51 -07005479 void updateCpuStats() {
5480 mH.post(mAmInternal::updateCpuStats);
5481 }
5482
Hui Yu03d12402018-12-06 18:00:37 -08005483 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5484 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005485 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5486 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005487 mH.sendMessage(m);
5488 }
5489
Hui Yu03d12402018-12-06 18:00:37 -08005490 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005491 ComponentName taskRoot = null;
5492 final TaskRecord task = activity.getTaskRecord();
5493 if (task != null) {
5494 final ActivityRecord rootActivity = task.getRootActivity();
5495 if (rootActivity != null) {
5496 taskRoot = rootActivity.mActivityComponent;
5497 }
5498 }
5499
Hui Yu03d12402018-12-06 18:00:37 -08005500 final Message m = PooledLambda.obtainMessage(
5501 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005502 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005503 mH.sendMessage(m);
5504 }
5505
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005506 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5507 String hostingType) {
5508 try {
5509 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5510 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5511 + activity.processName);
5512 }
5513 // Post message to start process to avoid possible deadlock of calling into AMS with the
5514 // ATMS lock held.
5515 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5516 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5517 isTop, hostingType, activity.intent.getComponent());
5518 mH.sendMessage(m);
5519 } finally {
5520 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5521 }
5522 }
5523
Wale Ogunwale53783742018-09-16 10:21:51 -07005524 void setBooting(boolean booting) {
5525 mAmInternal.setBooting(booting);
5526 }
5527
5528 boolean isBooting() {
5529 return mAmInternal.isBooting();
5530 }
5531
5532 void setBooted(boolean booted) {
5533 mAmInternal.setBooted(booted);
5534 }
5535
5536 boolean isBooted() {
5537 return mAmInternal.isBooted();
5538 }
5539
5540 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5541 mH.post(() -> {
5542 if (finishBooting) {
5543 mAmInternal.finishBooting();
5544 }
5545 if (enableScreen) {
5546 mInternal.enableScreenAfterBoot(isBooted());
5547 }
5548 });
5549 }
5550
5551 void setHeavyWeightProcess(ActivityRecord root) {
5552 mHeavyWeightProcess = root.app;
5553 final Message m = PooledLambda.obtainMessage(
5554 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005555 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005556 mH.sendMessage(m);
5557 }
5558
5559 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5560 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5561 return;
5562 }
5563
5564 mHeavyWeightProcess = null;
5565 final Message m = PooledLambda.obtainMessage(
5566 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5567 proc.mUserId);
5568 mH.sendMessage(m);
5569 }
5570
5571 private void cancelHeavyWeightProcessNotification(int userId) {
5572 final INotificationManager inm = NotificationManager.getService();
5573 if (inm == null) {
5574 return;
5575 }
5576 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005577 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005578 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5579 } catch (RuntimeException e) {
5580 Slog.w(TAG, "Error canceling notification for service", e);
5581 } catch (RemoteException e) {
5582 }
5583
5584 }
5585
5586 private void postHeavyWeightProcessNotification(
5587 WindowProcessController proc, Intent intent, int userId) {
5588 if (proc == null) {
5589 return;
5590 }
5591
5592 final INotificationManager inm = NotificationManager.getService();
5593 if (inm == null) {
5594 return;
5595 }
5596
5597 try {
5598 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5599 String text = mContext.getString(R.string.heavy_weight_notification,
5600 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5601 Notification notification =
5602 new Notification.Builder(context,
5603 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5604 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5605 .setWhen(0)
5606 .setOngoing(true)
5607 .setTicker(text)
5608 .setColor(mContext.getColor(
5609 com.android.internal.R.color.system_notification_accent_color))
5610 .setContentTitle(text)
5611 .setContentText(
5612 mContext.getText(R.string.heavy_weight_notification_detail))
5613 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5614 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5615 new UserHandle(userId)))
5616 .build();
5617 try {
5618 inm.enqueueNotificationWithTag("android", "android", null,
5619 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5620 } catch (RuntimeException e) {
5621 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5622 } catch (RemoteException e) {
5623 }
5624 } catch (PackageManager.NameNotFoundException e) {
5625 Slog.w(TAG, "Unable to create context for heavy notification", e);
5626 }
5627
5628 }
5629
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005630 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5631 IBinder token, String resultWho, int requestCode, Intent[] intents,
5632 String[] resolvedTypes, int flags, Bundle bOptions) {
5633
5634 ActivityRecord activity = null;
5635 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5636 activity = ActivityRecord.isInStackLocked(token);
5637 if (activity == null) {
5638 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5639 return null;
5640 }
5641 if (activity.finishing) {
5642 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5643 return null;
5644 }
5645 }
5646
5647 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5648 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5649 bOptions);
5650 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5651 if (noCreate) {
5652 return rec;
5653 }
5654 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5655 if (activity.pendingResults == null) {
5656 activity.pendingResults = new HashSet<>();
5657 }
5658 activity.pendingResults.add(rec.ref);
5659 }
5660 return rec;
5661 }
5662
Andrii Kulian52d255c2018-07-13 11:32:19 -07005663 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005664 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005665 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005666 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5667 mCurAppTimeTracker.start(resumedActivity.packageName);
5668 }
5669 }
5670
5671 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5672 if (mTracedResumedActivity != null) {
5673 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5674 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5675 }
5676 if (resumed != null) {
5677 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5678 constructResumedTraceName(resumed.packageName), 0);
5679 }
5680 mTracedResumedActivity = resumed;
5681 }
5682
5683 private String constructResumedTraceName(String packageName) {
5684 return "focused app: " + packageName;
5685 }
5686
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005687 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005688 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005689 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005690 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005691 // mainStack is null during startup.
5692 if (mainStack != null) {
5693 if (changes != 0 && starting == null) {
5694 // If the configuration changed, and the caller is not already
5695 // in the process of starting an activity, then find the top
5696 // activity to check if its configuration needs to change.
5697 starting = mainStack.topRunningActivityLocked();
5698 }
5699
5700 if (starting != null) {
5701 kept = starting.ensureActivityConfiguration(changes,
5702 false /* preserveWindow */);
5703 // And we need to make sure at this point that all other activities
5704 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005705 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005706 !PRESERVE_WINDOWS);
5707 }
5708 }
5709
5710 return kept;
5711 }
5712
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005713 void scheduleAppGcsLocked() {
5714 mH.post(() -> mAmInternal.scheduleAppGcs());
5715 }
5716
Wale Ogunwale53783742018-09-16 10:21:51 -07005717 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5718 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5719 }
5720
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005721 /**
5722 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5723 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5724 * on demand.
5725 */
5726 IPackageManager getPackageManager() {
5727 return AppGlobals.getPackageManager();
5728 }
5729
5730 PackageManagerInternal getPackageManagerInternalLocked() {
5731 if (mPmInternal == null) {
5732 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5733 }
5734 return mPmInternal;
5735 }
5736
Hai Zhangf4da9be2019-05-01 13:46:06 +08005737 PermissionPolicyInternal getPermissionPolicyInternal() {
5738 if (mPermissionPolicyInternal == null) {
5739 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5740 }
5741 return mPermissionPolicyInternal;
5742 }
5743
Wale Ogunwale008163e2018-07-23 23:11:08 -07005744 AppWarnings getAppWarningsLocked() {
5745 return mAppWarnings;
5746 }
5747
Wale Ogunwale214f3482018-10-04 11:00:47 -07005748 Intent getHomeIntent() {
5749 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5750 intent.setComponent(mTopComponent);
5751 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5752 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5753 intent.addCategory(Intent.CATEGORY_HOME);
5754 }
5755 return intent;
5756 }
5757
Chilun2ef71f72018-11-16 17:57:15 +08005758 /**
5759 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5760 * activities.
5761 *
5762 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5763 * component defined in config_secondaryHomeComponent.
5764 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5765 */
5766 Intent getSecondaryHomeIntent(String preferredPackage) {
5767 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005768 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5769 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5770 if (preferredPackage == null || useSystemProvidedLauncher) {
5771 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005772 final String secondaryHomeComponent = mContext.getResources().getString(
5773 com.android.internal.R.string.config_secondaryHomeComponent);
5774 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5775 } else {
5776 intent.setPackage(preferredPackage);
5777 }
5778 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5779 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5780 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5781 }
5782 return intent;
5783 }
5784
Wale Ogunwale214f3482018-10-04 11:00:47 -07005785 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5786 if (info == null) return null;
5787 ApplicationInfo newInfo = new ApplicationInfo(info);
5788 newInfo.initForUser(userId);
5789 return newInfo;
5790 }
5791
Wale Ogunwale9c103022018-10-18 07:44:54 -07005792 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005793 if (uid == SYSTEM_UID) {
5794 // The system gets to run in any process. If there are multiple processes with the same
5795 // uid, just pick the first (this should never happen).
5796 final SparseArray<WindowProcessController> procs =
5797 mProcessNames.getMap().get(processName);
5798 if (procs == null) return null;
5799 final int procCount = procs.size();
5800 for (int i = 0; i < procCount; i++) {
5801 final int procUid = procs.keyAt(i);
5802 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5803 // Don't use an app process or different user process for system component.
5804 continue;
5805 }
5806 return procs.valueAt(i);
5807 }
5808 }
5809
5810 return mProcessNames.get(processName, uid);
5811 }
5812
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005813 WindowProcessController getProcessController(IApplicationThread thread) {
5814 if (thread == null) {
5815 return null;
5816 }
5817
5818 final IBinder threadBinder = thread.asBinder();
5819 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5820 for (int i = pmap.size()-1; i >= 0; i--) {
5821 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5822 for (int j = procs.size() - 1; j >= 0; j--) {
5823 final WindowProcessController proc = procs.valueAt(j);
5824 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5825 return proc;
5826 }
5827 }
5828 }
5829
5830 return null;
5831 }
5832
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005833 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005834 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005835 if (proc == null) return null;
5836 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5837 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005838 }
5839 return null;
5840 }
5841
Riddle Hsua0536432019-02-16 00:38:59 +08005842 int getUidState(int uid) {
5843 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005844 }
5845
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005846 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005847 // A uid is considered to be foreground if it has a visible non-toast window.
5848 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005849 }
5850
Ricky Wai96f5c352019-04-10 18:40:17 +01005851 boolean isDeviceOwner(int uid) {
5852 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005853 }
5854
Ricky Wai96f5c352019-04-10 18:40:17 +01005855 void setDeviceOwnerUid(int uid) {
5856 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005857 }
5858
Wale Ogunwale9de19442018-10-18 19:05:03 -07005859 /**
5860 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5861 * the whitelist
5862 */
5863 String getPendingTempWhitelistTagForUidLocked(int uid) {
5864 return mPendingTempWhitelist.get(uid);
5865 }
5866
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005867 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5868 if (true || Build.IS_USER) {
5869 return;
5870 }
5871
5872 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5873 StrictMode.allowThreadDiskWrites();
5874 try {
5875 File tracesDir = new File("/data/anr");
5876 File tracesFile = null;
5877 try {
5878 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5879
5880 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005881 String timeString =
5882 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5883 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005884 sb.append(": ");
5885 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5886 sb.append(" since ");
5887 sb.append(msg);
5888 FileOutputStream fos = new FileOutputStream(tracesFile);
5889 fos.write(sb.toString().getBytes());
5890 if (app == null) {
5891 fos.write("\n*** No application process!".getBytes());
5892 }
5893 fos.close();
5894 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5895 } catch (IOException e) {
5896 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5897 return;
5898 }
5899
5900 if (app != null && app.getPid() > 0) {
5901 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5902 firstPids.add(app.getPid());
5903 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5904 }
5905
5906 File lastTracesFile = null;
5907 File curTracesFile = null;
5908 for (int i=9; i>=0; i--) {
5909 String name = String.format(Locale.US, "slow%02d.txt", i);
5910 curTracesFile = new File(tracesDir, name);
5911 if (curTracesFile.exists()) {
5912 if (lastTracesFile != null) {
5913 curTracesFile.renameTo(lastTracesFile);
5914 } else {
5915 curTracesFile.delete();
5916 }
5917 }
5918 lastTracesFile = curTracesFile;
5919 }
5920 tracesFile.renameTo(curTracesFile);
5921 } finally {
5922 StrictMode.setThreadPolicy(oldPolicy);
5923 }
5924 }
5925
Michal Karpinskida34cd42019-04-02 19:46:52 +01005926 boolean isAssociatedCompanionApp(int userId, int uid) {
5927 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5928 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005929 return false;
5930 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005931 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005932 }
5933
Issei Suzuki734bc942019-06-05 13:59:52 +02005934 void notifySingleTaskDisplayEmpty(int displayId) {
5935 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5936 }
5937
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005938 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005939 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005940
5941
Wale Ogunwale98875612018-10-12 07:53:02 -07005942 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5943 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005944
Riddle Hsud93a6c42018-11-29 21:50:06 +08005945 H(Looper looper) {
5946 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005947 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005948
5949 @Override
5950 public void handleMessage(Message msg) {
5951 switch (msg.what) {
5952 case REPORT_TIME_TRACKER_MSG: {
5953 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5954 tracker.deliverResult(mContext);
5955 } break;
5956 }
5957 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005958 }
5959
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005960 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005961 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005962
5963 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005964 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005965 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005966
5967 @Override
5968 public void handleMessage(Message msg) {
5969 switch (msg.what) {
5970 case DISMISS_DIALOG_UI_MSG: {
5971 final Dialog d = (Dialog) msg.obj;
5972 d.dismiss();
5973 break;
5974 }
5975 }
5976 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005977 }
5978
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005979 final class LocalService extends ActivityTaskManagerInternal {
5980 @Override
5981 public SleepToken acquireSleepToken(String tag, int displayId) {
5982 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005983 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005984 }
5985
5986 @Override
5987 public ComponentName getHomeActivityForUser(int userId) {
5988 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005989 final ActivityRecord homeActivity =
5990 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005991 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005992 }
5993 }
5994
5995 @Override
5996 public void onLocalVoiceInteractionStarted(IBinder activity,
5997 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5998 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005999 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006000 }
6001 }
6002
6003 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006004 public void notifyAppTransitionStarting(SparseIntArray reasons,
6005 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006006 synchronized (mGlobalLock) {
6007 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6008 reasons, timestamp);
6009 }
6010 }
6011
6012 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006013 public void notifySingleTaskDisplayDrawn(int displayId) {
6014 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6015 }
6016
6017 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006018 public void notifyAppTransitionFinished() {
6019 synchronized (mGlobalLock) {
6020 mStackSupervisor.notifyAppTransitionDone();
6021 }
6022 }
6023
6024 @Override
6025 public void notifyAppTransitionCancelled() {
6026 synchronized (mGlobalLock) {
6027 mStackSupervisor.notifyAppTransitionDone();
6028 }
6029 }
6030
6031 @Override
6032 public List<IBinder> getTopVisibleActivities() {
6033 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006034 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006035 }
6036 }
6037
6038 @Override
6039 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6040 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006041 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006042 }
6043 }
6044
6045 @Override
6046 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6047 Bundle bOptions) {
6048 Preconditions.checkNotNull(intents, "intents");
6049 final String[] resolvedTypes = new String[intents.length];
6050
6051 // UID of the package on user userId.
6052 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6053 // packageUid may not be initialized.
6054 int packageUid = 0;
6055 final long ident = Binder.clearCallingIdentity();
6056
6057 try {
6058 for (int i = 0; i < intents.length; i++) {
6059 resolvedTypes[i] =
6060 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6061 }
6062
6063 packageUid = AppGlobals.getPackageManager().getPackageUid(
6064 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6065 } catch (RemoteException e) {
6066 // Shouldn't happen.
6067 } finally {
6068 Binder.restoreCallingIdentity(ident);
6069 }
6070
Riddle Hsu591bf612019-02-14 17:55:31 +08006071 return getActivityStartController().startActivitiesInPackage(
6072 packageUid, packageName,
6073 intents, resolvedTypes, null /* resultTo */,
6074 SafeActivityOptions.fromBundle(bOptions), userId,
6075 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6076 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 }
6078
6079 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006080 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6081 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6082 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6083 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006084 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006085 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006086 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6087 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6088 userId, validateIncomingUser, originatingPendingIntent,
6089 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006090 }
6091 }
6092
6093 @Override
6094 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6095 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6096 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6097 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006098 PendingIntentRecord originatingPendingIntent,
6099 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006100 synchronized (mGlobalLock) {
6101 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6102 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6103 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006104 validateIncomingUser, originatingPendingIntent,
6105 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006106 }
6107 }
6108
6109 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006110 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6111 Intent intent, Bundle options, int userId) {
6112 return ActivityTaskManagerService.this.startActivityAsUser(
6113 caller, callerPacakge, intent,
6114 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6115 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6116 false /*validateIncomingUser*/);
6117 }
6118
6119 @Override
lumark588a3e82018-07-20 18:53:54 +08006120 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006121 synchronized (mGlobalLock) {
6122
6123 // We might change the visibilities here, so prepare an empty app transition which
6124 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006125 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006126 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006127 if (activityDisplay == null) {
6128 return;
6129 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006130 final DisplayContent dc = activityDisplay.mDisplayContent;
6131 final boolean wasTransitionSet =
6132 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006134 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006136 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006137
6138 // If there was a transition set already we don't want to interfere with it as we
6139 // might be starting it too early.
6140 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006141 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006142 }
6143 }
6144 if (callback != null) {
6145 callback.run();
6146 }
6147 }
6148
6149 @Override
6150 public void notifyKeyguardTrustedChanged() {
6151 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006152 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006153 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 }
6155 }
6156 }
6157
6158 /**
6159 * Called after virtual display Id is updated by
6160 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6161 * {@param vrVr2dDisplayId}.
6162 */
6163 @Override
6164 public void setVr2dDisplayId(int vr2dDisplayId) {
6165 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6166 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006167 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006168 }
6169 }
6170
6171 @Override
6172 public void setFocusedActivity(IBinder token) {
6173 synchronized (mGlobalLock) {
6174 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6175 if (r == null) {
6176 throw new IllegalArgumentException(
6177 "setFocusedActivity: No activity record matching token=" + token);
6178 }
Louis Chang19443452018-10-09 12:10:21 +08006179 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006180 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182 }
6183 }
6184
6185 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006187 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 }
6189
6190 @Override
6191 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006192 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006193 }
6194
6195 @Override
6196 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006197 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198 }
6199
6200 @Override
6201 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6202 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6203 }
6204
6205 @Override
6206 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006207 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006208 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006209
6210 @Override
6211 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6212 synchronized (mGlobalLock) {
6213 mActiveVoiceInteractionServiceComponent = component;
6214 }
6215 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006216
6217 @Override
6218 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6219 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6220 return;
6221 }
6222 synchronized (mGlobalLock) {
6223 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6224 if (types == null) {
6225 if (uid < 0) {
6226 return;
6227 }
6228 types = new ArrayMap<>();
6229 mAllowAppSwitchUids.put(userId, types);
6230 }
6231 if (uid < 0) {
6232 types.remove(type);
6233 } else {
6234 types.put(type, uid);
6235 }
6236 }
6237 }
6238
6239 @Override
6240 public void onUserStopped(int userId) {
6241 synchronized (mGlobalLock) {
6242 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6243 mAllowAppSwitchUids.remove(userId);
6244 }
6245 }
6246
6247 @Override
6248 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6249 synchronized (mGlobalLock) {
6250 return ActivityTaskManagerService.this.isGetTasksAllowed(
6251 caller, callingPid, callingUid);
6252 }
6253 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006254
Riddle Hsua0536432019-02-16 00:38:59 +08006255 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006256 @Override
6257 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006258 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006259 mProcessNames.put(proc.mName, proc.mUid, proc);
6260 }
6261 }
6262
Riddle Hsua0536432019-02-16 00:38:59 +08006263 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006264 @Override
6265 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006266 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006267 mProcessNames.remove(name, uid);
6268 }
6269 }
6270
Riddle Hsua0536432019-02-16 00:38:59 +08006271 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006272 @Override
6273 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006274 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006275 if (proc == mHomeProcess) {
6276 mHomeProcess = null;
6277 }
6278 if (proc == mPreviousProcess) {
6279 mPreviousProcess = null;
6280 }
6281 }
6282 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006283
Riddle Hsua0536432019-02-16 00:38:59 +08006284 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006285 @Override
6286 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006287 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006288 return mTopProcessState;
6289 }
6290 }
6291
Riddle Hsua0536432019-02-16 00:38:59 +08006292 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006293 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006294 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006295 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006296 return proc == mHeavyWeightProcess;
6297 }
6298 }
6299
Riddle Hsua0536432019-02-16 00:38:59 +08006300 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006301 @Override
6302 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006303 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006304 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6305 }
6306 }
6307
6308 @Override
6309 public void finishHeavyWeightApp() {
6310 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006311 if (mHeavyWeightProcess != null) {
6312 mHeavyWeightProcess.finishActivities();
6313 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006314 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6315 mHeavyWeightProcess);
6316 }
6317 }
6318
Riddle Hsua0536432019-02-16 00:38:59 +08006319 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006320 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006321 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006322 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006323 return isSleepingLocked();
6324 }
6325 }
6326
6327 @Override
6328 public boolean isShuttingDown() {
6329 synchronized (mGlobalLock) {
6330 return mShuttingDown;
6331 }
6332 }
6333
6334 @Override
6335 public boolean shuttingDown(boolean booted, int timeout) {
6336 synchronized (mGlobalLock) {
6337 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006338 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006339 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006340 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006341 return mStackSupervisor.shutdownLocked(timeout);
6342 }
6343 }
6344
6345 @Override
6346 public void enableScreenAfterBoot(boolean booted) {
6347 synchronized (mGlobalLock) {
6348 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6349 SystemClock.uptimeMillis());
6350 mWindowManager.enableScreenAfterBoot();
6351 updateEventDispatchingLocked(booted);
6352 }
6353 }
6354
6355 @Override
6356 public boolean showStrictModeViolationDialog() {
6357 synchronized (mGlobalLock) {
6358 return mShowDialogs && !mSleeping && !mShuttingDown;
6359 }
6360 }
6361
6362 @Override
6363 public void showSystemReadyErrorDialogsIfNeeded() {
6364 synchronized (mGlobalLock) {
6365 try {
6366 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6367 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6368 + " data partition or your device will be unstable.");
6369 mUiHandler.post(() -> {
6370 if (mShowDialogs) {
6371 AlertDialog d = new BaseErrorDialog(mUiContext);
6372 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6373 d.setCancelable(false);
6374 d.setTitle(mUiContext.getText(R.string.android_system_label));
6375 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6376 d.setButton(DialogInterface.BUTTON_POSITIVE,
6377 mUiContext.getText(R.string.ok),
6378 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6379 d.show();
6380 }
6381 });
6382 }
6383 } catch (RemoteException e) {
6384 }
6385
6386 if (!Build.isBuildConsistent()) {
6387 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6388 mUiHandler.post(() -> {
6389 if (mShowDialogs) {
6390 AlertDialog d = new BaseErrorDialog(mUiContext);
6391 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6392 d.setCancelable(false);
6393 d.setTitle(mUiContext.getText(R.string.android_system_label));
6394 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6395 d.setButton(DialogInterface.BUTTON_POSITIVE,
6396 mUiContext.getText(R.string.ok),
6397 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6398 d.show();
6399 }
6400 });
6401 }
6402 }
6403 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006404
6405 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006406 public void onProcessMapped(int pid, WindowProcessController proc) {
6407 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006408 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006409 }
6410 }
6411
6412 @Override
6413 public void onProcessUnMapped(int pid) {
6414 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006415 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006416 }
6417 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006418
6419 @Override
6420 public void onPackageDataCleared(String name) {
6421 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006423 mAppWarnings.onPackageDataCleared(name);
6424 }
6425 }
6426
6427 @Override
6428 public void onPackageUninstalled(String name) {
6429 synchronized (mGlobalLock) {
6430 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006431 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006432 }
6433 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006434
6435 @Override
6436 public void onPackageAdded(String name, boolean replacing) {
6437 synchronized (mGlobalLock) {
6438 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6439 }
6440 }
6441
6442 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006443 public void onPackageReplaced(ApplicationInfo aInfo) {
6444 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006445 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006446 }
6447 }
6448
6449 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006450 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6451 synchronized (mGlobalLock) {
6452 return compatibilityInfoForPackageLocked(ai);
6453 }
6454 }
6455
Yunfan Chen75157d72018-07-27 14:47:21 +09006456 /**
6457 * Set the corresponding display information for the process global configuration. To be
6458 * called when we need to show IME on a different display.
6459 *
6460 * @param pid The process id associated with the IME window.
6461 * @param displayId The ID of the display showing the IME.
6462 */
6463 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006464 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006465 // Don't update process-level configuration for Multi-Client IME process since other
6466 // IMEs on other displays will also receive this configuration change due to IME
6467 // services use the same application config/context.
6468 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006469
Yunfan Chen75157d72018-07-27 14:47:21 +09006470 if (pid == MY_PID || pid < 0) {
6471 if (DEBUG_CONFIGURATION) {
6472 Slog.w(TAG,
6473 "Trying to update display configuration for system/invalid process.");
6474 }
6475 return;
6476 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006477 synchronized (mGlobalLock) {
6478 final ActivityDisplay activityDisplay =
6479 mRootActivityContainer.getActivityDisplay(displayId);
6480 if (activityDisplay == null) {
6481 // Call might come when display is not yet added or has been removed.
6482 if (DEBUG_CONFIGURATION) {
6483 Slog.w(TAG, "Trying to update display configuration for non-existing "
6484 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006485 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006486 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006487 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006488 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006489 if (process == null) {
6490 if (DEBUG_CONFIGURATION) {
6491 Slog.w(TAG, "Trying to update display configuration for invalid "
6492 + "process, pid=" + pid);
6493 }
6494 return;
6495 }
lumarkddc77fb2019-06-27 22:22:23 +08006496 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006497 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6498 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006499 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006500
6501 @Override
6502 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006503 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006504 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006505 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6506 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006507 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006508 }
6509 }
6510 }
6511
6512 @Override
6513 public void clearPendingResultForActivity(IBinder activityToken,
6514 WeakReference<PendingIntentRecord> pir) {
6515 synchronized (mGlobalLock) {
6516 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6517 if (r != null && r.pendingResults != null) {
6518 r.pendingResults.remove(pir);
6519 }
6520 }
6521 }
6522
6523 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006524 public ActivityTokens getTopActivityForTask(int taskId) {
6525 synchronized (mGlobalLock) {
6526 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6527 if (taskRecord == null) {
6528 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6529 + " Requested task not found");
6530 return null;
6531 }
6532 final ActivityRecord activity = taskRecord.getTopActivity();
6533 if (activity == null) {
6534 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6535 + " Requested activity not found");
6536 return null;
6537 }
6538 if (!activity.attachedToProcess()) {
6539 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6540 + activity);
6541 return null;
6542 }
6543 return new ActivityTokens(activity.appToken, activity.assistToken,
6544 activity.app.getThread());
6545 }
6546 }
6547
6548 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006549 public IIntentSender getIntentSender(int type, String packageName,
6550 int callingUid, int userId, IBinder token, String resultWho,
6551 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6552 Bundle bOptions) {
6553 synchronized (mGlobalLock) {
6554 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6555 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6556 }
6557 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006558
6559 @Override
6560 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6561 synchronized (mGlobalLock) {
6562 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6563 if (r == null) {
6564 return null;
6565 }
6566 if (r.mServiceConnectionsHolder == null) {
6567 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6568 ActivityTaskManagerService.this, r);
6569 }
6570
6571 return r.mServiceConnectionsHolder;
6572 }
6573 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006574
6575 @Override
6576 public Intent getHomeIntent() {
6577 synchronized (mGlobalLock) {
6578 return ActivityTaskManagerService.this.getHomeIntent();
6579 }
6580 }
6581
6582 @Override
6583 public boolean startHomeActivity(int userId, String reason) {
6584 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006585 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006586 }
6587 }
6588
6589 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006590 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006591 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006592 synchronized (mGlobalLock) {
6593 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006594 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006595 }
Chilun8b1f1be2019-03-13 17:14:36 +08006596 }
6597
6598 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006599 public boolean startHomeOnAllDisplays(int userId, String reason) {
6600 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006601 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006602 }
6603 }
6604
Riddle Hsua0536432019-02-16 00:38:59 +08006605 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006606 @Override
6607 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006608 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006609 if (mFactoryTest == FACTORY_TEST_OFF) {
6610 return false;
6611 }
6612 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6613 && wpc.mName.equals(mTopComponent.getPackageName())) {
6614 return true;
6615 }
6616 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6617 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6618 }
6619 }
6620
6621 @Override
6622 public void updateTopComponentForFactoryTest() {
6623 synchronized (mGlobalLock) {
6624 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6625 return;
6626 }
6627 final ResolveInfo ri = mContext.getPackageManager()
6628 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6629 final CharSequence errorMsg;
6630 if (ri != null) {
6631 final ActivityInfo ai = ri.activityInfo;
6632 final ApplicationInfo app = ai.applicationInfo;
6633 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6634 mTopAction = Intent.ACTION_FACTORY_TEST;
6635 mTopData = null;
6636 mTopComponent = new ComponentName(app.packageName, ai.name);
6637 errorMsg = null;
6638 } else {
6639 errorMsg = mContext.getResources().getText(
6640 com.android.internal.R.string.factorytest_not_system);
6641 }
6642 } else {
6643 errorMsg = mContext.getResources().getText(
6644 com.android.internal.R.string.factorytest_no_action);
6645 }
6646 if (errorMsg == null) {
6647 return;
6648 }
6649
6650 mTopAction = null;
6651 mTopData = null;
6652 mTopComponent = null;
6653 mUiHandler.post(() -> {
6654 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6655 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006656 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006657 });
6658 }
6659 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660
Riddle Hsua0536432019-02-16 00:38:59 +08006661 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006662 @Override
6663 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6664 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006665 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006666 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006667 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006668
6669 wpc.clearRecentTasks();
6670 wpc.clearActivities();
6671
6672 if (wpc.isInstrumenting()) {
6673 finishInstrumentationCallback.run();
6674 }
6675
Jorim Jaggid0752812018-10-16 16:07:20 +02006676 if (!restarting && hasVisibleActivities) {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006677 deferWindowLayout();
Jorim Jaggid0752812018-10-16 16:07:20 +02006678 try {
6679 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6680 // If there was nothing to resume, and we are not already restarting
6681 // this process, but there is a visible activity that is hosted by the
6682 // process...then make sure all visible activities are running, taking
6683 // care of restarting this process.
6684 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6685 !PRESERVE_WINDOWS);
6686 }
6687 } finally {
Riddle Hsua0022cd2019-09-09 21:12:41 +08006688 continueWindowLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006689 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006690 }
6691 }
6692 }
6693
6694 @Override
6695 public void closeSystemDialogs(String reason) {
6696 enforceNotIsolatedCaller("closeSystemDialogs");
6697
6698 final int pid = Binder.getCallingPid();
6699 final int uid = Binder.getCallingUid();
6700 final long origId = Binder.clearCallingIdentity();
6701 try {
6702 synchronized (mGlobalLock) {
6703 // Only allow this from foreground processes, so that background
6704 // applications can't abuse it to prevent system UI from being shown.
6705 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006706 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 if (!proc.isPerceptible()) {
6708 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6709 + " from background process " + proc);
6710 return;
6711 }
6712 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 mWindowManager.closeSystemDialogs(reason);
6714
Wale Ogunwaled32da472018-11-16 07:19:28 -08006715 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006717 // Call into AM outside the synchronized block.
6718 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006719 } finally {
6720 Binder.restoreCallingIdentity(origId);
6721 }
6722 }
6723
6724 @Override
6725 public void cleanupDisabledPackageComponents(
6726 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6727 synchronized (mGlobalLock) {
6728 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006729 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006731 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006732 mStackSupervisor.scheduleIdleLocked();
6733 }
6734
6735 // Clean-up disabled tasks
6736 getRecentTasks().cleanupDisabledPackageTasksLocked(
6737 packageName, disabledClasses, userId);
6738 }
6739 }
6740
6741 @Override
6742 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6743 int userId) {
6744 synchronized (mGlobalLock) {
6745
6746 boolean didSomething =
6747 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006748 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 null, doit, evenPersistent, userId);
6750 return didSomething;
6751 }
6752 }
6753
6754 @Override
6755 public void resumeTopActivities(boolean scheduleIdle) {
6756 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006757 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 if (scheduleIdle) {
6759 mStackSupervisor.scheduleIdleLocked();
6760 }
6761 }
6762 }
6763
Riddle Hsua0536432019-02-16 00:38:59 +08006764 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 @Override
6766 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006767 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006768 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6769 }
6770 }
6771
Riddle Hsua0536432019-02-16 00:38:59 +08006772 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 @Override
6774 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006775 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006776 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777 }
6778 }
6779
6780 @Override
6781 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6782 try {
6783 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6784 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6785 }
6786 } catch (RemoteException ex) {
6787 throw new SecurityException("Fail to check is caller a privileged app", ex);
6788 }
6789
6790 synchronized (mGlobalLock) {
6791 final long ident = Binder.clearCallingIdentity();
6792 try {
6793 if (mAmInternal.shouldConfirmCredentials(userId)) {
6794 if (mKeyguardController.isKeyguardLocked()) {
6795 // Showing launcher to avoid user entering credential twice.
6796 startHomeActivity(currentUserId, "notifyLockedProfile");
6797 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006798 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 }
6800 } finally {
6801 Binder.restoreCallingIdentity(ident);
6802 }
6803 }
6804 }
6805
6806 @Override
6807 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6808 mAmInternal.enforceCallingPermission(
6809 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6810
6811 synchronized (mGlobalLock) {
6812 final long ident = Binder.clearCallingIdentity();
6813 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006814 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6815 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6818 UserHandle.CURRENT);
6819 } finally {
6820 Binder.restoreCallingIdentity(ident);
6821 }
6822 }
6823 }
6824
6825 @Override
6826 public void writeActivitiesToProto(ProtoOutputStream proto) {
6827 synchronized (mGlobalLock) {
6828 // The output proto of "activity --proto activities"
6829 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006830 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006831 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6832 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 }
6834 }
6835
6836 @Override
6837 public void saveANRState(String reason) {
6838 synchronized (mGlobalLock) {
6839 final StringWriter sw = new StringWriter();
6840 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6841 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6842 if (reason != null) {
6843 pw.println(" Reason: " + reason);
6844 }
6845 pw.println();
6846 getActivityStartController().dump(pw, " ", null);
6847 pw.println();
6848 pw.println("-------------------------------------------------------------------------------");
6849 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6850 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6851 "" /* header */);
6852 pw.println();
6853 pw.close();
6854
6855 mLastANRState = sw.toString();
6856 }
6857 }
6858
6859 @Override
6860 public void clearSavedANRState() {
6861 synchronized (mGlobalLock) {
6862 mLastANRState = null;
6863 }
6864 }
6865
6866 @Override
6867 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6868 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6869 synchronized (mGlobalLock) {
6870 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6871 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6872 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6873 dumpLastANRLocked(pw);
6874 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6875 dumpLastANRTracesLocked(pw);
6876 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6877 dumpActivityStarterLocked(pw, dumpPackage);
6878 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6879 dumpActivityContainersLocked(pw);
6880 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6881 if (getRecentTasks() != null) {
6882 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6883 }
6884 }
6885 }
6886 }
6887
6888 @Override
6889 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6890 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6891 int wakefulness) {
6892 synchronized (mGlobalLock) {
6893 if (mHomeProcess != null && (dumpPackage == null
6894 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6895 if (needSep) {
6896 pw.println();
6897 needSep = false;
6898 }
6899 pw.println(" mHomeProcess: " + mHomeProcess);
6900 }
6901 if (mPreviousProcess != null && (dumpPackage == null
6902 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6903 if (needSep) {
6904 pw.println();
6905 needSep = false;
6906 }
6907 pw.println(" mPreviousProcess: " + mPreviousProcess);
6908 }
6909 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6910 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6911 StringBuilder sb = new StringBuilder(128);
6912 sb.append(" mPreviousProcessVisibleTime: ");
6913 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6914 pw.println(sb);
6915 }
6916 if (mHeavyWeightProcess != null && (dumpPackage == null
6917 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6918 if (needSep) {
6919 pw.println();
6920 needSep = false;
6921 }
6922 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6923 }
6924 if (dumpPackage == null) {
6925 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006926 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006927 }
6928 if (dumpAll) {
6929 if (dumpPackage == null) {
6930 pw.println(" mConfigWillChange: "
6931 + getTopDisplayFocusedStack().mConfigWillChange);
6932 }
6933 if (mCompatModePackages.getPackages().size() > 0) {
6934 boolean printed = false;
6935 for (Map.Entry<String, Integer> entry
6936 : mCompatModePackages.getPackages().entrySet()) {
6937 String pkg = entry.getKey();
6938 int mode = entry.getValue();
6939 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6940 continue;
6941 }
6942 if (!printed) {
6943 pw.println(" mScreenCompatPackages:");
6944 printed = true;
6945 }
6946 pw.println(" " + pkg + ": " + mode);
6947 }
6948 }
6949 }
6950
6951 if (dumpPackage == null) {
6952 pw.println(" mWakefulness="
6953 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006954 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006955 if (mRunningVoice != null) {
6956 pw.println(" mRunningVoice=" + mRunningVoice);
6957 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6958 }
6959 pw.println(" mSleeping=" + mSleeping);
6960 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6961 pw.println(" mVrController=" + mVrController);
6962 }
6963 if (mCurAppTimeTracker != null) {
6964 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6965 }
6966 if (mAllowAppSwitchUids.size() > 0) {
6967 boolean printed = false;
6968 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6969 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6970 for (int j = 0; j < types.size(); j++) {
6971 if (dumpPackage == null ||
6972 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6973 if (needSep) {
6974 pw.println();
6975 needSep = false;
6976 }
6977 if (!printed) {
6978 pw.println(" mAllowAppSwitchUids:");
6979 printed = true;
6980 }
6981 pw.print(" User ");
6982 pw.print(mAllowAppSwitchUids.keyAt(i));
6983 pw.print(": Type ");
6984 pw.print(types.keyAt(j));
6985 pw.print(" = ");
6986 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6987 pw.println();
6988 }
6989 }
6990 }
6991 }
6992 if (dumpPackage == null) {
6993 if (mController != null) {
6994 pw.println(" mController=" + mController
6995 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6996 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006997 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6998 pw.println(" mLaunchingActivityWakeLock="
6999 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007000 }
7001
7002 return needSep;
7003 }
7004 }
7005
7006 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007007 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7008 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007009 synchronized (mGlobalLock) {
7010 if (dumpPackage == null) {
7011 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7012 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007013 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7014 if (mRunningVoice != null) {
7015 final long vrToken = proto.start(
7016 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7017 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7018 mRunningVoice.toString());
7019 mVoiceWakeLock.writeToProto(
7020 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7021 proto.end(vrToken);
7022 }
7023 mVrController.writeToProto(proto,
7024 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 if (mController != null) {
7026 final long token = proto.start(CONTROLLER);
7027 proto.write(CONTROLLER, mController.toString());
7028 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7029 proto.end(token);
7030 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007031 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7032 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7033 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007034 }
7035
7036 if (mHomeProcess != null && (dumpPackage == null
7037 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007038 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007039 }
7040
7041 if (mPreviousProcess != null && (dumpPackage == null
7042 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007043 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007044 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7045 }
7046
7047 if (mHeavyWeightProcess != null && (dumpPackage == null
7048 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007049 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007050 }
7051
7052 for (Map.Entry<String, Integer> entry
7053 : mCompatModePackages.getPackages().entrySet()) {
7054 String pkg = entry.getKey();
7055 int mode = entry.getValue();
7056 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7057 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7058 proto.write(PACKAGE, pkg);
7059 proto.write(MODE, mode);
7060 proto.end(compatToken);
7061 }
7062 }
7063
7064 if (mCurAppTimeTracker != null) {
7065 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7066 }
7067
7068 }
7069 }
7070
7071 @Override
7072 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7073 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7074 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007075 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7076 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 }
7078
7079 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007080 public void dumpForOom(PrintWriter pw) {
7081 synchronized (mGlobalLock) {
7082 pw.println(" mHomeProcess: " + mHomeProcess);
7083 pw.println(" mPreviousProcess: " + mPreviousProcess);
7084 if (mHeavyWeightProcess != null) {
7085 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7086 }
7087 }
7088 }
7089
7090 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007091 public boolean canGcNow() {
7092 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007093 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007094 }
7095 }
7096
Riddle Hsua0536432019-02-16 00:38:59 +08007097 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007098 @Override
7099 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007100 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007101 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 return top != null ? top.app : null;
7103 }
7104 }
7105
Riddle Hsua0536432019-02-16 00:38:59 +08007106 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007107 @Override
7108 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007109 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007110 if (mRootActivityContainer != null) {
7111 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007112 }
7113 }
7114 }
7115
7116 @Override
7117 public void scheduleDestroyAllActivities(String reason) {
7118 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007119 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 }
7121 }
7122
7123 @Override
7124 public void removeUser(int userId) {
7125 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007126 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128 }
7129
7130 @Override
7131 public boolean switchUser(int userId, UserState userState) {
7132 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007133 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 }
7135 }
7136
7137 @Override
7138 public void onHandleAppCrash(WindowProcessController wpc) {
7139 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007140 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007141 }
7142 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007143
7144 @Override
7145 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7146 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007147 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007148 }
7149 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007150
Riddle Hsua0536432019-02-16 00:38:59 +08007151 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007152 @Override
7153 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007154 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007155 }
7156
Riddle Hsua0536432019-02-16 00:38:59 +08007157 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007158 @Override
7159 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007160 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007161 }
7162
Riddle Hsua0536432019-02-16 00:38:59 +08007163 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007164 @Override
7165 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007166 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007167 }
7168
Riddle Hsua0536432019-02-16 00:38:59 +08007169 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007170 @Override
7171 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007172 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007173 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007174
7175 @Override
7176 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007177 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007178 mPendingTempWhitelist.put(uid, tag);
7179 }
7180 }
7181
7182 @Override
7183 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007184 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007185 mPendingTempWhitelist.remove(uid);
7186 }
7187 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007188
7189 @Override
7190 public boolean handleAppCrashInActivityController(String processName, int pid,
7191 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7192 Runnable killCrashingAppCallback) {
7193 synchronized (mGlobalLock) {
7194 if (mController == null) {
7195 return false;
7196 }
7197
7198 try {
7199 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7200 stackTrace)) {
7201 killCrashingAppCallback.run();
7202 return true;
7203 }
7204 } catch (RemoteException e) {
7205 mController = null;
7206 Watchdog.getInstance().setActivityController(null);
7207 }
7208 return false;
7209 }
7210 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007211
7212 @Override
7213 public void removeRecentTasksByPackageName(String packageName, int userId) {
7214 synchronized (mGlobalLock) {
7215 mRecentTasks.removeTasksByPackageName(packageName, userId);
7216 }
7217 }
7218
7219 @Override
7220 public void cleanupRecentTasksForUser(int userId) {
7221 synchronized (mGlobalLock) {
7222 mRecentTasks.cleanupLocked(userId);
7223 }
7224 }
7225
7226 @Override
7227 public void loadRecentTasksForUser(int userId) {
7228 synchronized (mGlobalLock) {
7229 mRecentTasks.loadUserRecentsLocked(userId);
7230 }
7231 }
7232
7233 @Override
7234 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7235 synchronized (mGlobalLock) {
7236 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7237 }
7238 }
7239
7240 @Override
7241 public void flushRecentTasks() {
7242 mRecentTasks.flush();
7243 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007244
7245 @Override
7246 public WindowProcessController getHomeProcess() {
7247 synchronized (mGlobalLock) {
7248 return mHomeProcess;
7249 }
7250 }
7251
7252 @Override
7253 public WindowProcessController getPreviousProcess() {
7254 synchronized (mGlobalLock) {
7255 return mPreviousProcess;
7256 }
7257 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007258
7259 @Override
7260 public void clearLockedTasks(String reason) {
7261 synchronized (mGlobalLock) {
7262 getLockTaskController().clearLockedTasks(reason);
7263 }
7264 }
7265
7266 @Override
7267 public void updateUserConfiguration() {
7268 synchronized (mGlobalLock) {
7269 final Configuration configuration = new Configuration(getGlobalConfiguration());
7270 final int currentUserId = mAmInternal.getCurrentUserId();
7271 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7272 configuration, currentUserId, Settings.System.canWrite(mContext));
7273 updateConfigurationLocked(configuration, null /* starting */,
7274 false /* initLocale */, false /* persistent */, currentUserId,
7275 false /* deferResume */);
7276 }
7277 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007278
7279 @Override
7280 public boolean canShowErrorDialogs() {
7281 synchronized (mGlobalLock) {
7282 return mShowDialogs && !mSleeping && !mShuttingDown
7283 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7284 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7285 mAmInternal.getCurrentUserId())
7286 && !(UserManager.isDeviceInDemoMode(mContext)
7287 && mAmInternal.getCurrentUser().isDemo());
7288 }
7289 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007290
7291 @Override
7292 public void setProfileApp(String profileApp) {
7293 synchronized (mGlobalLock) {
7294 mProfileApp = profileApp;
7295 }
7296 }
7297
7298 @Override
7299 public void setProfileProc(WindowProcessController wpc) {
7300 synchronized (mGlobalLock) {
7301 mProfileProc = wpc;
7302 }
7303 }
7304
7305 @Override
7306 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7307 synchronized (mGlobalLock) {
7308 mProfilerInfo = profilerInfo;
7309 }
7310 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007311
7312 @Override
7313 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7314 synchronized (mGlobalLock) {
7315 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7316 }
7317 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007318
7319 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007320 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7321 boolean reducedResolution) {
7322 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7323 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007324 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007325
7326 @Override
7327 public boolean isUidForeground(int uid) {
7328 synchronized (mGlobalLock) {
7329 return ActivityTaskManagerService.this.isUidForeground(uid);
7330 }
7331 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007332
7333 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007334 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007335 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007336 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007337 }
7338 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007339
7340 @Override
7341 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007342 // Translate package names into UIDs
7343 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007344 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007345 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7346 if (uid >= 0) {
7347 result.add(uid);
7348 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007349 }
7350 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007351 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007352 }
7353 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007354 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007355}