blob: f2ca2ba82dfb494ac6ab99857044237fffdc496b [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;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070047import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
Wale Ogunwale214f3482018-10-04 11:00:47 -070049import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
50import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
51import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070052import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070053import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070054import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070055import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
56import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
57import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
59import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070060import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040061import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.view.Display.DEFAULT_DISPLAY;
63import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070064import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
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;
Andrii Kulian7dd39bb2019-07-22 13:11:10 -070090import static com.android.server.wm.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
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;
217import android.util.EventLog;
218import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700219import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700221import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700222import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700223import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700224import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700225import android.view.IRecentsAnimationRunner;
226import android.view.RemoteAnimationAdapter;
227import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700228import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700249import com.android.server.LocalServices;
250import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800252import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900263import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700265import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700268import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700272import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700275import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700276import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700277import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700278import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800279import java.lang.annotation.ElementType;
280import java.lang.annotation.Retention;
281import java.lang.annotation.RetentionPolicy;
282import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700285import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700286import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700287import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400288import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700289import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700290import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700291import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700292import java.util.Map;
293import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294
295/**
296 * System service for managing activities and their containers (task, stacks, displays,... ).
297 *
298 * {@hide}
299 */
300public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700301 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700303 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
304 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
305 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
306 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
307 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700308 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700309
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700310 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700311 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700312 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700313 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100314 // How long we permit background activity starts after an activity in the process
315 // started or finished.
316 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700317
Wale Ogunwale98875612018-10-12 07:53:02 -0700318 /** Used to indicate that an app transition should be animated. */
319 static final boolean ANIMATE = true;
320
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700321 /** Hardware-reported OpenGLES version. */
322 final int GL_ES_VERSION;
323
Wale Ogunwale31913b52018-10-13 08:29:31 -0700324 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
325 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
326 public static final String DUMP_LASTANR_CMD = "lastanr" ;
327 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
328 public static final String DUMP_STARTER_CMD = "starter" ;
329 public static final String DUMP_CONTAINERS_CMD = "containers" ;
330 public static final String DUMP_RECENTS_CMD = "recents" ;
331 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
332
Wale Ogunwale64258362018-10-16 15:13:37 -0700333 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
334 public static final int RELAUNCH_REASON_NONE = 0;
335 /** This activity is being relaunched due to windowing mode change. */
336 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
337 /** This activity is being relaunched due to a free-resize operation. */
338 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
339
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700340 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700341
Wale Ogunwalef6733932018-06-27 05:14:34 -0700342 /**
343 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
344 * change at runtime. Use mContext for non-UI purposes.
345 */
346 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700347 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700348 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700351 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700352 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800353 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800354 @VisibleForTesting
355 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700356 PowerManagerInternal mPowerManagerInternal;
357 private UsageStatsManagerInternal mUsageStatsInternal;
358
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700359 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700360 IntentFirewall mIntentFirewall;
361
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700362 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800363 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800364 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700365 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800366 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
367 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
368 *
369 * @see WindowManagerThreadPriorityBooster
370 */
371 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700372 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800373 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700374 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700375 private UserManagerService mUserManager;
376 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700377 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800378 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700379 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700380 /** All processes currently running that might have a window organized by name. */
381 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100382 /** All processes we currently have running mapped by pid and uid */
383 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /** This is the process holding what we currently consider to be the "home" activity. */
385 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700386 /** The currently running heavy-weight process, if any. */
387 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700388 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700389 /**
390 * This is the process holding the activity the user last visited that is in a different process
391 * from the one they are currently in.
392 */
393 WindowProcessController mPreviousProcess;
394 /** The time at which the previous process was last visible. */
395 long mPreviousProcessVisibleTime;
396
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700397 /** List of intents that were used to start the most recent tasks. */
398 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700399 /** State of external calls telling us if the device is awake or asleep. */
400 private boolean mKeyguardShown = false;
401
402 // Wrapper around VoiceInteractionServiceManager
403 private AssistUtils mAssistUtils;
404
405 // VoiceInteraction session ID that changes for each new request except when
406 // being called for multi-window assist in a single session.
407 private int mViSessionId = 1000;
408
409 // How long to wait in getAssistContextExtras for the activity and foreground services
410 // to respond with the result.
411 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
412
413 // How long top wait when going through the modern assist (which doesn't need to block
414 // on getting this result before starting to launch its UI).
415 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
416
417 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
418 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
419
Alison Cichowlas3e340502018-08-07 17:15:01 -0400420 // Permission tokens are used to temporarily granted a trusted app the ability to call
421 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
422 // showing any appropriate error messages to the user.
423 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
424 10 * MINUTE_IN_MILLIS;
425
426 // How long before the service actually expires a token. This is slightly longer than
427 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
428 // expiration exception.
429 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
430 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
431
432 // How long the service will remember expired tokens, for the purpose of providing error
433 // messaging when a client uses an expired token.
434 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
435 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
436
437 // Activity tokens of system activities that are delegating their call to
438 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
439 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
440
441 // Permission tokens that have expired, but we remember for error reporting.
442 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
443
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700444 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
445
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700446 // Keeps track of the active voice interaction service component, notified from
447 // VoiceInteractionManagerService
448 ComponentName mActiveVoiceInteractionServiceComponent;
449
Michal Karpinskida34cd42019-04-02 19:46:52 +0100450 // A map userId and all its companion app uids
451 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000452
Wale Ogunwalee2172292018-10-25 10:11:10 -0700453 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700454 KeyguardController mKeyguardController;
455 private final ClientLifecycleManager mLifecycleManager;
456 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700457 /** The controller for all operations related to locktask. */
458 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700459 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700460
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700461 boolean mSuppressResizeConfigChanges;
462
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700463 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700464 new UpdateConfigurationResult();
465
466 static final class UpdateConfigurationResult {
467 // Configuration changes that were updated.
468 int changes;
469 // If the activity was relaunched to match the new configuration.
470 boolean activityRelaunched;
471
472 void reset() {
473 changes = 0;
474 activityRelaunched = false;
475 }
476 }
477
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700478 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 private int mConfigurationSeq;
480 // To cache the list of supported system locales
481 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482
483 /**
484 * Temp object used when global and/or display override configuration is updated. It is also
485 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
486 * anyone...
487 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488 private Configuration mTempConfig = new Configuration();
489
Wale Ogunwalef6733932018-06-27 05:14:34 -0700490 /** Temporary to avoid allocations. */
491 final StringBuilder mStringBuilder = new StringBuilder(256);
492
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700493 // Amount of time after a call to stopAppSwitches() during which we will
494 // prevent further untrusted switches from happening.
495 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
496
497 /**
498 * The time at which we will allow normal application switches again,
499 * after a call to {@link #stopAppSwitches()}.
500 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700501 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700502 /**
503 * This is set to true after the first switch after mAppSwitchesAllowedTime
504 * is set; any switches after that will clear the time.
505 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700506 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507
Ricky Wai906af482019-06-03 17:25:28 +0100508 /**
509 * Last stop app switches time, apps finished before this time cannot start background activity
510 * even if they are in grace period.
511 */
512 private long mLastStopAppSwitchesTime;
513
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700514 IActivityController mController = null;
515 boolean mControllerIsAMonkey = false;
516
Wale Ogunwale214f3482018-10-04 11:00:47 -0700517 final int mFactoryTest;
518
519 /** Used to control how we initialize the service. */
520 ComponentName mTopComponent;
521 String mTopAction = Intent.ACTION_MAIN;
522 String mTopData;
523
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800524 /** Profiling app information. */
525 String mProfileApp = null;
526 WindowProcessController mProfileProc = null;
527 ProfilerInfo mProfilerInfo = null;
528
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700529 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700530 * Dump of the activity state at the time of the last ANR. Cleared after
531 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
532 */
533 String mLastANRState;
534
535 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700536 * Used to retain an update lock when the foreground activity is in
537 * immersive mode.
538 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700539 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540
541 /**
542 * Packages that are being allowed to perform unrestricted app switches. Mapping is
543 * User -> Type -> uid.
544 */
545 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
546
547 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700548 private int mThumbnailWidth;
549 private int mThumbnailHeight;
550 private float mFullscreenThumbnailScale;
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
599 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
600 // automatically. Important for devices without direct input devices.
601 private boolean mShowDialogs = true;
602
603 /** Set if we are shutting down the system, similar to sleeping. */
604 boolean mShuttingDown = false;
605
606 /**
607 * We want to hold a wake lock while running a voice interaction session, since
608 * this may happen with the screen off and we need to keep the CPU running to
609 * be able to continue to interact with the user.
610 */
611 PowerManager.WakeLock mVoiceWakeLock;
612
613 /**
614 * Set while we are running a voice interaction. This overrides sleeping while it is active.
615 */
616 IVoiceInteractionSession mRunningVoice;
617
618 /**
619 * The last resumed activity. This is identical to the current resumed activity most
620 * of the time but could be different when we're pausing one activity before we resume
621 * another activity.
622 */
623 ActivityRecord mLastResumedActivity;
624
625 /**
626 * The activity that is currently being traced as the active resumed activity.
627 *
628 * @see #updateResumedAppTrace
629 */
630 private @Nullable ActivityRecord mTracedResumedActivity;
631
632 /** If non-null, we are tracking the time the user spends in the currently focused app. */
633 AppTimeTracker mCurAppTimeTracker;
634
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700635 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700636
Wale Ogunwale53783742018-09-16 10:21:51 -0700637 /**
638 * Packages that the user has asked to have run in screen size
639 * compatibility mode instead of filling the screen.
640 */
641 CompatModePackages mCompatModePackages;
642
Wale Ogunwalef6733932018-06-27 05:14:34 -0700643 private FontScaleSettingObserver mFontScaleSettingObserver;
644
Ricky Wai96f5c352019-04-10 18:40:17 +0100645 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000646
Wale Ogunwalef6733932018-06-27 05:14:34 -0700647 private final class FontScaleSettingObserver extends ContentObserver {
648 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
649 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
650
651 public FontScaleSettingObserver() {
652 super(mH);
653 final ContentResolver resolver = mContext.getContentResolver();
654 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
655 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
656 UserHandle.USER_ALL);
657 }
658
659 @Override
660 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
661 if (mFontScaleUri.equals(uri)) {
662 updateFontScaleIfNeeded(userId);
663 } else if (mHideErrorDialogsUri.equals(uri)) {
664 synchronized (mGlobalLock) {
665 updateShouldShowDialogsLocked(getGlobalConfiguration());
666 }
667 }
668 }
669 }
670
Riddle Hsua0536432019-02-16 00:38:59 +0800671 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
672 @Target(ElementType.METHOD)
673 @Retention(RetentionPolicy.SOURCE)
674 @interface HotPath {
675 int NONE = 0;
676 int OOM_ADJUSTMENT = 1;
677 int LRU_UPDATE = 2;
678 int PROCESS_CHANGE = 3;
679 int caller() default NONE;
680 }
681
Charles Chen8d98dd22018-12-26 17:36:54 +0800682 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
683 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700684 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700685 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700686 mSystemThread = ActivityThread.currentActivityThread();
687 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700688 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800689 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700690 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700691 }
692
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700693 public void onSystemReady() {
694 synchronized (mGlobalLock) {
695 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
696 PackageManager.FEATURE_CANT_SAVE_STATE);
697 mAssistUtils = new AssistUtils(mContext);
698 mVrController.onSystemReady();
699 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700700 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700701 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700702 }
703
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700704 public void onInitPowerManagement() {
705 synchronized (mGlobalLock) {
706 mStackSupervisor.initPowerManagement();
707 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
708 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
709 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
710 mVoiceWakeLock.setReferenceCounted(false);
711 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700712 }
713
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700714 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700715 mFontScaleSettingObserver = new FontScaleSettingObserver();
716 }
717
Wale Ogunwale59507092018-10-29 09:00:30 -0700718 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700719 final boolean freeformWindowManagement =
720 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
721 || Settings.Global.getInt(
722 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
723
724 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
725 final boolean supportsPictureInPicture = supportsMultiWindow &&
726 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
727 final boolean supportsSplitScreenMultiWindow =
728 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
729 final boolean supportsMultiDisplay = mContext.getPackageManager()
730 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700731 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
732 final boolean forceResizable = Settings.Global.getInt(
733 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
734
735 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900736 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737
738 final Configuration configuration = new Configuration();
739 Settings.System.getConfiguration(resolver, configuration);
740 if (forceRtl) {
741 // This will take care of setting the correct layout direction flags
742 configuration.setLayoutDirection(configuration.locale);
743 }
744
745 synchronized (mGlobalLock) {
746 mForceResizableActivities = forceResizable;
747 final boolean multiWindowFormEnabled = freeformWindowManagement
748 || supportsSplitScreenMultiWindow
749 || supportsPictureInPicture
750 || supportsMultiDisplay;
751 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
752 mSupportsMultiWindow = true;
753 mSupportsFreeformWindowManagement = freeformWindowManagement;
754 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
755 mSupportsPictureInPicture = supportsPictureInPicture;
756 mSupportsMultiDisplay = supportsMultiDisplay;
757 } else {
758 mSupportsMultiWindow = false;
759 mSupportsFreeformWindowManagement = false;
760 mSupportsSplitScreenMultiWindow = false;
761 mSupportsPictureInPicture = false;
762 mSupportsMultiDisplay = false;
763 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700764 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700765 // This happens before any activities are started, so we can change global configuration
766 // in-place.
767 updateConfigurationLocked(configuration, null, true);
768 final Configuration globalConfig = getGlobalConfiguration();
769 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
770
771 // Load resources only after the current configuration has been set.
772 final Resources res = mContext.getResources();
773 mThumbnailWidth = res.getDimensionPixelSize(
774 com.android.internal.R.dimen.thumbnail_width);
775 mThumbnailHeight = res.getDimensionPixelSize(
776 com.android.internal.R.dimen.thumbnail_height);
777
778 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
779 mFullscreenThumbnailScale = (float) res
780 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
781 (float) globalConfig.screenWidthDp;
782 } else {
783 mFullscreenThumbnailScale = res.getFraction(
784 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
785 }
786 }
787 }
788
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800789 public WindowManagerGlobalLock getGlobalLock() {
790 return mGlobalLock;
791 }
792
Yunfan Chen585f2932019-01-29 16:04:45 +0900793 /** For test purpose only. */
794 @VisibleForTesting
795 public ActivityTaskManagerInternal getAtmInternal() {
796 return mInternal;
797 }
798
Riddle Hsud93a6c42018-11-29 21:50:06 +0800799 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
800 Looper looper) {
801 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700802 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700803 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700804 final File systemDir = SystemServiceManager.ensureSystemDir();
805 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
806 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700808
809 mTempConfig.setToDefaults();
810 mTempConfig.setLocales(LocaleList.getDefault());
811 mConfigurationSeq = mTempConfig.seq = 1;
812 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800813 mRootActivityContainer = new RootActivityContainer(this);
814 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700815
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700816 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700817 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700818 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700820 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700822 mKeyguardController = mStackSupervisor.getKeyguardController();
823 }
824
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700825 public void onActivityManagerInternalAdded() {
826 synchronized (mGlobalLock) {
827 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
828 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
829 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700830 }
831
Yunfan Chen75157d72018-07-27 14:47:21 +0900832 int increaseConfigurationSeqLocked() {
833 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
834 return mConfigurationSeq;
835 }
836
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700837 protected ActivityStackSupervisor createStackSupervisor() {
838 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
839 supervisor.initialize();
840 return supervisor;
841 }
842
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700843 public void setWindowManager(WindowManagerService wm) {
844 synchronized (mGlobalLock) {
845 mWindowManager = wm;
846 mLockTaskController.setWindowManager(wm);
847 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800848 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700849 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700850 }
851
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700852 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
853 synchronized (mGlobalLock) {
854 mUsageStatsInternal = usageStatsManager;
855 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700856 }
857
Wale Ogunwalef6733932018-06-27 05:14:34 -0700858 UserManagerService getUserManager() {
859 if (mUserManager == null) {
860 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
861 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
862 }
863 return mUserManager;
864 }
865
866 AppOpsService getAppOpsService() {
867 if (mAppOpsService == null) {
868 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
869 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
870 }
871 return mAppOpsService;
872 }
873
874 boolean hasUserRestriction(String restriction, int userId) {
875 return getUserManager().hasUserRestriction(restriction, userId);
876 }
877
Michal Karpinski15486842019-04-25 17:33:42 +0100878 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
879 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
880 callingUid, callingPackage);
881 if (mode == AppOpsManager.MODE_DEFAULT) {
882 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
883 == PERMISSION_GRANTED;
884 }
885 return mode == AppOpsManager.MODE_ALLOWED;
886 }
887
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700888 @VisibleForTesting
889 protected void setRecentTasks(RecentTasks recentTasks) {
890 mRecentTasks = recentTasks;
891 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700892 }
893
894 RecentTasks getRecentTasks() {
895 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700896 }
897
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700898 ClientLifecycleManager getLifecycleManager() {
899 return mLifecycleManager;
900 }
901
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700902 ActivityStartController getActivityStartController() {
903 return mActivityStartController;
904 }
905
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700906 TaskChangeNotificationController getTaskChangeNotificationController() {
907 return mTaskChangeNotificationController;
908 }
909
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700910 LockTaskController getLockTaskController() {
911 return mLockTaskController;
912 }
913
Yunfan Chen75157d72018-07-27 14:47:21 +0900914 /**
915 * Return the global configuration used by the process corresponding to the input pid. This is
916 * usually the global configuration with some overrides specific to that process.
917 */
918 Configuration getGlobalConfigurationForCallingPid() {
919 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800920 return getGlobalConfigurationForPid(pid);
921 }
922
923 /**
924 * Return the global configuration used by the process corresponding to the given pid.
925 */
926 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900927 if (pid == MY_PID || pid < 0) {
928 return getGlobalConfiguration();
929 }
930 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100931 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900932 return app != null ? app.getConfiguration() : getGlobalConfiguration();
933 }
934 }
935
936 /**
937 * Return the device configuration info used by the process corresponding to the input pid.
938 * The value is consistent with the global configuration for the process.
939 */
940 @Override
941 public ConfigurationInfo getDeviceConfigurationInfo() {
942 ConfigurationInfo config = new ConfigurationInfo();
943 synchronized (mGlobalLock) {
944 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
945 config.reqTouchScreen = globalConfig.touchscreen;
946 config.reqKeyboardType = globalConfig.keyboard;
947 config.reqNavigation = globalConfig.navigation;
948 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
949 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
950 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
951 }
952 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
953 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
954 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
955 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700956 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900957 }
958 return config;
959 }
960
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700961 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700962 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700963 }
964
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700965 public static final class Lifecycle extends SystemService {
966 private final ActivityTaskManagerService mService;
967
968 public Lifecycle(Context context) {
969 super(context);
970 mService = new ActivityTaskManagerService(context);
971 }
972
973 @Override
974 public void onStart() {
975 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700976 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700977 }
978
Garfield Tan891146c2018-10-09 12:14:00 -0700979 @Override
980 public void onUnlockUser(int userId) {
981 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800982 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700983 }
984 }
985
986 @Override
987 public void onCleanupUser(int userId) {
988 synchronized (mService.getGlobalLock()) {
989 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
990 }
991 }
992
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700993 public ActivityTaskManagerService getService() {
994 return mService;
995 }
996 }
997
998 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700999 public final int startActivity(IApplicationThread caller, String callingPackage,
1000 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1001 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1002 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1003 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1004 UserHandle.getCallingUserId());
1005 }
1006
1007 @Override
1008 public final int startActivities(IApplicationThread caller, String callingPackage,
1009 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1010 int userId) {
1011 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001012 enforceNotIsolatedCaller(reason);
1013 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001014 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001015 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1016 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1017 reason, null /* originatingPendingIntent */,
1018 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 }
1020
1021 @Override
1022 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1023 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1024 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1025 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1026 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1027 true /*validateIncomingUser*/);
1028 }
1029
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001030 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001031 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1032 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1033 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001034 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001036 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1038
1039 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001040 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001041 .setCaller(caller)
1042 .setCallingPackage(callingPackage)
1043 .setResolvedType(resolvedType)
1044 .setResultTo(resultTo)
1045 .setResultWho(resultWho)
1046 .setRequestCode(requestCode)
1047 .setStartFlags(startFlags)
1048 .setProfilerInfo(profilerInfo)
1049 .setActivityOptions(bOptions)
1050 .setMayWait(userId)
1051 .execute();
1052
1053 }
1054
1055 @Override
1056 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1057 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001058 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1059 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 // Refuse possible leaked file descriptors
1061 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1062 throw new IllegalArgumentException("File descriptors passed in Intent");
1063 }
1064
1065 if (!(target instanceof PendingIntentRecord)) {
1066 throw new IllegalArgumentException("Bad PendingIntent object");
1067 }
1068
1069 PendingIntentRecord pir = (PendingIntentRecord)target;
1070
1071 synchronized (mGlobalLock) {
1072 // If this is coming from the currently resumed activity, it is
1073 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001074 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001075 if (stack.mResumedActivity != null &&
1076 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001077 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 }
1079 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001080 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 }
1083
1084 @Override
1085 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1086 Bundle bOptions) {
1087 // Refuse possible leaked file descriptors
1088 if (intent != null && intent.hasFileDescriptors()) {
1089 throw new IllegalArgumentException("File descriptors passed in Intent");
1090 }
1091 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1092
1093 synchronized (mGlobalLock) {
1094 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1095 if (r == null) {
1096 SafeActivityOptions.abort(options);
1097 return false;
1098 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001099 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001100 // The caller is not running... d'oh!
1101 SafeActivityOptions.abort(options);
1102 return false;
1103 }
1104 intent = new Intent(intent);
1105 // The caller is not allowed to change the data.
1106 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1107 // And we are resetting to find the next component...
1108 intent.setComponent(null);
1109
1110 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1111
1112 ActivityInfo aInfo = null;
1113 try {
1114 List<ResolveInfo> resolves =
1115 AppGlobals.getPackageManager().queryIntentActivities(
1116 intent, r.resolvedType,
1117 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1118 UserHandle.getCallingUserId()).getList();
1119
1120 // Look for the original activity in the list...
1121 final int N = resolves != null ? resolves.size() : 0;
1122 for (int i=0; i<N; i++) {
1123 ResolveInfo rInfo = resolves.get(i);
1124 if (rInfo.activityInfo.packageName.equals(r.packageName)
1125 && rInfo.activityInfo.name.equals(r.info.name)) {
1126 // We found the current one... the next matching is
1127 // after it.
1128 i++;
1129 if (i<N) {
1130 aInfo = resolves.get(i).activityInfo;
1131 }
1132 if (debug) {
1133 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1134 + "/" + r.info.name);
1135 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1136 ? "null" : aInfo.packageName + "/" + aInfo.name));
1137 }
1138 break;
1139 }
1140 }
1141 } catch (RemoteException e) {
1142 }
1143
1144 if (aInfo == null) {
1145 // Nobody who is next!
1146 SafeActivityOptions.abort(options);
1147 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1148 return false;
1149 }
1150
1151 intent.setComponent(new ComponentName(
1152 aInfo.applicationInfo.packageName, aInfo.name));
1153 intent.setFlags(intent.getFlags()&~(
1154 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1155 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1156 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1157 FLAG_ACTIVITY_NEW_TASK));
1158
1159 // Okay now we need to start the new activity, replacing the currently running activity.
1160 // This is a little tricky because we want to start the new one as if the current one is
1161 // finished, but not finish the current one first so that there is no flicker.
1162 // And thus...
1163 final boolean wasFinishing = r.finishing;
1164 r.finishing = true;
1165
1166 // Propagate reply information over to the new activity.
1167 final ActivityRecord resultTo = r.resultTo;
1168 final String resultWho = r.resultWho;
1169 final int requestCode = r.requestCode;
1170 r.resultTo = null;
1171 if (resultTo != null) {
1172 resultTo.removeResultsLocked(r, resultWho, requestCode);
1173 }
1174
1175 final long origId = Binder.clearCallingIdentity();
1176 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001177 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001178 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001179 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001180 .setResolvedType(r.resolvedType)
1181 .setActivityInfo(aInfo)
1182 .setResultTo(resultTo != null ? resultTo.appToken : null)
1183 .setResultWho(resultWho)
1184 .setRequestCode(requestCode)
1185 .setCallingPid(-1)
1186 .setCallingUid(r.launchedFromUid)
1187 .setCallingPackage(r.launchedFromPackage)
1188 .setRealCallingPid(-1)
1189 .setRealCallingUid(r.launchedFromUid)
1190 .setActivityOptions(options)
1191 .execute();
1192 Binder.restoreCallingIdentity(origId);
1193
1194 r.finishing = wasFinishing;
1195 if (res != ActivityManager.START_SUCCESS) {
1196 return false;
1197 }
1198 return true;
1199 }
1200 }
1201
1202 @Override
1203 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1204 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1205 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1206 final WaitResult res = new WaitResult();
1207 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001208 enforceNotIsolatedCaller("startActivityAndWait");
1209 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1210 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001212 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001213 .setCaller(caller)
1214 .setCallingPackage(callingPackage)
1215 .setResolvedType(resolvedType)
1216 .setResultTo(resultTo)
1217 .setResultWho(resultWho)
1218 .setRequestCode(requestCode)
1219 .setStartFlags(startFlags)
1220 .setActivityOptions(bOptions)
1221 .setMayWait(userId)
1222 .setProfilerInfo(profilerInfo)
1223 .setWaitResult(res)
1224 .execute();
1225 }
1226 return res;
1227 }
1228
1229 @Override
1230 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1231 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1232 int startFlags, Configuration config, Bundle bOptions, int userId) {
1233 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001234 enforceNotIsolatedCaller("startActivityWithConfig");
1235 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1236 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001238 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001239 .setCaller(caller)
1240 .setCallingPackage(callingPackage)
1241 .setResolvedType(resolvedType)
1242 .setResultTo(resultTo)
1243 .setResultWho(resultWho)
1244 .setRequestCode(requestCode)
1245 .setStartFlags(startFlags)
1246 .setGlobalConfiguration(config)
1247 .setActivityOptions(bOptions)
1248 .setMayWait(userId)
1249 .execute();
1250 }
1251 }
1252
Alison Cichowlas3e340502018-08-07 17:15:01 -04001253
1254 @Override
1255 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1256 int callingUid = Binder.getCallingUid();
1257 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1258 throw new SecurityException("Only the system process can request a permission token, "
1259 + "received request from uid: " + callingUid);
1260 }
1261 IBinder permissionToken = new Binder();
1262 synchronized (mGlobalLock) {
1263 mStartActivitySources.put(permissionToken, delegatorToken);
1264 }
1265
1266 Message expireMsg = PooledLambda.obtainMessage(
1267 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1268 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1269
1270 Message forgetMsg = PooledLambda.obtainMessage(
1271 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1272 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1273
1274 return permissionToken;
1275 }
1276
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001277 @Override
1278 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1279 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001280 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1281 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001282 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283 // permission grants) as any app that may launch one of your own activities. So we only
1284 // allow this in two cases:
1285 // 1) The caller is an activity that is part of the core framework, and then only when it
1286 // is running as the system.
1287 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1288 // can only be requested by a system activity, which may then delegate this call to
1289 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 final ActivityRecord sourceRecord;
1291 final int targetUid;
1292 final String targetPackage;
1293 final boolean isResolver;
1294 synchronized (mGlobalLock) {
1295 if (resultTo == null) {
1296 throw new SecurityException("Must be called from an activity");
1297 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001298 final IBinder sourceToken;
1299 if (permissionToken != null) {
1300 // To even attempt to use a permissionToken, an app must also have this signature
1301 // permission.
1302 mAmInternal.enforceCallingPermission(
1303 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1304 "startActivityAsCaller");
1305 // If called with a permissionToken, we want the sourceRecord from the delegator
1306 // activity that requested this token.
1307 sourceToken = mStartActivitySources.remove(permissionToken);
1308 if (sourceToken == null) {
1309 // Invalid permissionToken, check if it recently expired.
1310 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1311 throw new SecurityException("Called with expired permission token: "
1312 + permissionToken);
1313 } else {
1314 throw new SecurityException("Called with invalid permission token: "
1315 + permissionToken);
1316 }
1317 }
1318 } else {
1319 // This method was called directly by the source.
1320 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001321 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001322
Wale Ogunwaled32da472018-11-16 07:19:28 -08001323 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001324 if (sourceRecord == null) {
1325 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001326 }
1327 if (sourceRecord.app == null) {
1328 throw new SecurityException("Called without a process attached to activity");
1329 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001330
1331 // Whether called directly or from a delegate, the source activity must be from the
1332 // android package.
1333 if (!sourceRecord.info.packageName.equals("android")) {
1334 throw new SecurityException("Must be called from an activity that is "
1335 + "declared in the android package");
1336 }
1337
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001338 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001339 // This is still okay, as long as this activity is running under the
1340 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001343 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 + " must be system uid or original calling uid "
1345 + sourceRecord.launchedFromUid);
1346 }
1347 }
1348 if (ignoreTargetSecurity) {
1349 if (intent.getComponent() == null) {
1350 throw new SecurityException(
1351 "Component must be specified with ignoreTargetSecurity");
1352 }
1353 if (intent.getSelector() != null) {
1354 throw new SecurityException(
1355 "Selector not allowed with ignoreTargetSecurity");
1356 }
1357 }
1358 targetUid = sourceRecord.launchedFromUid;
1359 targetPackage = sourceRecord.launchedFromPackage;
1360 isResolver = sourceRecord.isResolverOrChildActivity();
1361 }
1362
1363 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001364 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001365 }
1366
1367 // TODO: Switch to user app stacks here.
1368 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001369 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 .setCallingUid(targetUid)
1371 .setCallingPackage(targetPackage)
1372 .setResolvedType(resolvedType)
1373 .setResultTo(resultTo)
1374 .setResultWho(resultWho)
1375 .setRequestCode(requestCode)
1376 .setStartFlags(startFlags)
1377 .setActivityOptions(bOptions)
1378 .setMayWait(userId)
1379 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1380 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001381 // The target may well be in the background, which would normally prevent it
1382 // from starting an activity. Here we definitely want the start to succeed.
1383 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001384 .execute();
1385 } catch (SecurityException e) {
1386 // XXX need to figure out how to propagate to original app.
1387 // A SecurityException here is generally actually a fault of the original
1388 // calling activity (such as a fairly granting permissions), so propagate it
1389 // back to them.
1390 /*
1391 StringBuilder msg = new StringBuilder();
1392 msg.append("While launching");
1393 msg.append(intent.toString());
1394 msg.append(": ");
1395 msg.append(e.getMessage());
1396 */
1397 throw e;
1398 }
1399 }
1400
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001401 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1402 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1403 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1404 }
1405
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001406 @Override
1407 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1408 Intent intent, String resolvedType, IVoiceInteractionSession session,
1409 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1410 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 if (session == null || interactor == null) {
1413 throw new NullPointerException("null session or interactor");
1414 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001415 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001416 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001417 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001418 .setCallingUid(callingUid)
1419 .setCallingPackage(callingPackage)
1420 .setResolvedType(resolvedType)
1421 .setVoiceSession(session)
1422 .setVoiceInteractor(interactor)
1423 .setStartFlags(startFlags)
1424 .setProfilerInfo(profilerInfo)
1425 .setActivityOptions(bOptions)
1426 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001427 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 .execute();
1429 }
1430
1431 @Override
1432 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1433 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001434 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1435 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001437 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 .setCallingUid(callingUid)
1439 .setCallingPackage(callingPackage)
1440 .setResolvedType(resolvedType)
1441 .setActivityOptions(bOptions)
1442 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001443 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 .execute();
1445 }
1446
Riddle Hsu609a8e22019-06-27 16:46:29 -06001447 /**
1448 * Start the recents activity to perform the recents animation.
1449 *
1450 * @param intent The intent to start the recents activity.
1451 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1452 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001453 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001454 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1455 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001456 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001457 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001458 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 final long origId = Binder.clearCallingIdentity();
1460 try {
1461 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001462 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1463 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001464 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465
1466 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001467 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001468 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001469 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001470 if (recentsAnimationRunner == null) {
1471 anim.preloadRecentsActivity();
1472 } else {
1473 anim.startRecentsActivity(recentsAnimationRunner);
1474 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 }
1476 } finally {
1477 Binder.restoreCallingIdentity(origId);
1478 }
1479 }
1480
1481 @Override
1482 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001483 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001484 "startActivityFromRecents()");
1485
1486 final int callingPid = Binder.getCallingPid();
1487 final int callingUid = Binder.getCallingUid();
1488 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1489 final long origId = Binder.clearCallingIdentity();
1490 try {
1491 synchronized (mGlobalLock) {
1492 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1493 safeOptions);
1494 }
1495 } finally {
1496 Binder.restoreCallingIdentity(origId);
1497 }
1498 }
1499
1500 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001501 * Public API to check if the client is allowed to start an activity on specified display.
1502 *
1503 * If the target display is private or virtual, some restrictions will apply.
1504 *
1505 * @param displayId Target display id.
1506 * @param intent Intent used to launch the activity.
1507 * @param resolvedType The MIME type of the intent.
1508 * @param userId The id of the user for whom the call is made.
1509 * @return {@code true} if a call to start an activity on the target display should succeed and
1510 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1511 */
1512 @Override
1513 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1514 String resolvedType, int userId) {
1515 final int callingUid = Binder.getCallingUid();
1516 final int callingPid = Binder.getCallingPid();
1517 final long origId = Binder.clearCallingIdentity();
1518
1519 try {
1520 // Collect information about the target of the Intent.
1521 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1522 0 /* startFlags */, null /* profilerInfo */, userId,
1523 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1524 UserHandle.USER_NULL));
1525 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1526
1527 synchronized (mGlobalLock) {
1528 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1529 aInfo);
1530 }
1531 } finally {
1532 Binder.restoreCallingIdentity(origId);
1533 }
1534 }
1535
1536 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001537 * This is the internal entry point for handling Activity.finish().
1538 *
1539 * @param token The Binder token referencing the Activity we want to finish.
1540 * @param resultCode Result code, if any, from this Activity.
1541 * @param resultData Result data (Intent), if any, from this Activity.
1542 * @param finishTask Whether to finish the task associated with this Activity.
1543 *
1544 * @return Returns true if the activity successfully finished, or false if it is still running.
1545 */
1546 @Override
1547 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1548 int finishTask) {
1549 // Refuse possible leaked file descriptors
1550 if (resultData != null && resultData.hasFileDescriptors()) {
1551 throw new IllegalArgumentException("File descriptors passed in Intent");
1552 }
1553
1554 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001556 if (r == null) {
1557 return true;
1558 }
1559 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001560 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001561 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001562 if (rootR == null) {
1563 Slog.w(TAG, "Finishing task with all activities already finished");
1564 }
1565 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1566 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001567 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001568 return false;
1569 }
1570
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001571 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1572 // We should consolidate.
1573 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001575 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 if (next != null) {
1577 // ask watcher if this is allowed
1578 boolean resumeOK = true;
1579 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001580 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001581 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001582 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001583 Watchdog.getInstance().setActivityController(null);
1584 }
1585
1586 if (!resumeOK) {
1587 Slog.i(TAG, "Not finishing activity because controller resumed");
1588 return false;
1589 }
1590 }
1591 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001592
1593 // note down that the process has finished an activity and is in background activity
1594 // starts grace period
1595 if (r.app != null) {
1596 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1597 }
1598
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001599 final long origId = Binder.clearCallingIdentity();
1600 try {
1601 boolean res;
1602 final boolean finishWithRootActivity =
1603 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1604 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1605 || (finishWithRootActivity && r == rootR)) {
1606 // If requested, remove the task that is associated to this activity only if it
1607 // was the root activity in the task. The result code and data is ignored
1608 // because we don't support returning them across task boundaries. Also, to
1609 // keep backwards compatibility we remove the task from recents when finishing
1610 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001611 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001612 finishWithRootActivity, "finish-activity");
1613 if (!res) {
1614 Slog.i(TAG, "Removing task failed to finish activity");
1615 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001616 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001617 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 } else {
Andrii Kulian7dd39bb2019-07-22 13:11:10 -07001619 r.finishIfPossible(resultCode, resultData, "app-request",
1620 true /* oomAdj */, !PAUSE_IMMEDIATELY);
Andrii Kulian40eda672019-07-30 15:05:57 -07001621 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 if (!res) {
1623 Slog.i(TAG, "Failed to finish by app-request");
1624 }
1625 }
1626 return res;
1627 } finally {
1628 Binder.restoreCallingIdentity(origId);
1629 }
1630 }
1631 }
1632
1633 @Override
1634 public boolean finishActivityAffinity(IBinder token) {
1635 synchronized (mGlobalLock) {
1636 final long origId = Binder.clearCallingIdentity();
1637 try {
1638 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1639 if (r == null) {
1640 return false;
1641 }
1642
1643 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1644 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001645 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001646 return false;
1647 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001648 r.finishActivityAffinity();
1649 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 } finally {
1651 Binder.restoreCallingIdentity(origId);
1652 }
1653 }
1654 }
1655
1656 @Override
1657 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1658 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001659 try {
1660 WindowProcessController proc = null;
1661 synchronized (mGlobalLock) {
1662 ActivityStack stack = ActivityRecord.getStackLocked(token);
1663 if (stack == null) {
1664 return;
1665 }
1666 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1667 false /* fromTimeout */, false /* processPausingActivities */, config);
1668 if (r != null) {
1669 proc = r.app;
1670 }
1671 if (stopProfiling && proc != null) {
1672 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 }
1674 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001675 } finally {
1676 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 }
1679
1680 @Override
1681 public final void activityResumed(IBinder token) {
1682 final long origId = Binder.clearCallingIdentity();
1683 synchronized (mGlobalLock) {
1684 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001685 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 }
1687 Binder.restoreCallingIdentity(origId);
1688 }
1689
1690 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001691 public final void activityTopResumedStateLost() {
1692 final long origId = Binder.clearCallingIdentity();
1693 synchronized (mGlobalLock) {
1694 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1695 }
1696 Binder.restoreCallingIdentity(origId);
1697 }
1698
1699 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 public final void activityPaused(IBinder token) {
1701 final long origId = Binder.clearCallingIdentity();
1702 synchronized (mGlobalLock) {
1703 ActivityStack stack = ActivityRecord.getStackLocked(token);
1704 if (stack != null) {
1705 stack.activityPausedLocked(token, false);
1706 }
1707 }
1708 Binder.restoreCallingIdentity(origId);
1709 }
1710
1711 @Override
1712 public final void activityStopped(IBinder token, Bundle icicle,
1713 PersistableBundle persistentState, CharSequence description) {
1714 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1715
1716 // Refuse possible leaked file descriptors
1717 if (icicle != null && icicle.hasFileDescriptors()) {
1718 throw new IllegalArgumentException("File descriptors passed in Bundle");
1719 }
1720
1721 final long origId = Binder.clearCallingIdentity();
1722
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001723 String restartingName = null;
1724 int restartingUid = 0;
1725 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001727 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001729 if (r.attachedToProcess()
1730 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1731 // The activity was requested to restart from
1732 // {@link #restartActivityProcessIfVisible}.
1733 restartingName = r.app.mName;
1734 restartingUid = r.app.mUid;
1735 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 r.activityStoppedLocked(icicle, persistentState, description);
1737 }
1738 }
1739
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001740 if (restartingName != null) {
1741 // In order to let the foreground activity can be restarted with its saved state from
1742 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1743 // until the activity reports stopped with the state. And the activity record will be
1744 // kept because the record state is restarting, then the activity will be restarted
1745 // immediately if it is still the top one.
1746 mStackSupervisor.removeRestartTimeouts(r);
1747 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1748 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001749 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001750
1751 Binder.restoreCallingIdentity(origId);
1752 }
1753
1754 @Override
1755 public final void activityDestroyed(IBinder token) {
1756 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1757 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001758 final long origId = Binder.clearCallingIdentity();
1759 try {
1760 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1761 if (activity != null) {
1762 activity.destroyed("activityDestroyed");
1763 }
1764 } finally {
1765 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 }
1767 }
1768 }
1769
1770 @Override
1771 public final void activityRelaunched(IBinder token) {
1772 final long origId = Binder.clearCallingIdentity();
1773 synchronized (mGlobalLock) {
1774 mStackSupervisor.activityRelaunchedLocked(token);
1775 }
1776 Binder.restoreCallingIdentity(origId);
1777 }
1778
1779 public final void activitySlept(IBinder token) {
1780 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1781
1782 final long origId = Binder.clearCallingIdentity();
1783
1784 synchronized (mGlobalLock) {
1785 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1786 if (r != null) {
1787 mStackSupervisor.activitySleptLocked(r);
1788 }
1789 }
1790
1791 Binder.restoreCallingIdentity(origId);
1792 }
1793
1794 @Override
1795 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1796 synchronized (mGlobalLock) {
1797 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1798 if (r == null) {
1799 return;
1800 }
1801 final long origId = Binder.clearCallingIdentity();
1802 try {
1803 r.setRequestedOrientation(requestedOrientation);
1804 } finally {
1805 Binder.restoreCallingIdentity(origId);
1806 }
1807 }
1808 }
1809
1810 @Override
1811 public int getRequestedOrientation(IBinder token) {
1812 synchronized (mGlobalLock) {
1813 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1814 if (r == null) {
1815 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1816 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001817 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 }
1819 }
1820
1821 @Override
1822 public void setImmersive(IBinder token, boolean immersive) {
1823 synchronized (mGlobalLock) {
1824 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1825 if (r == null) {
1826 throw new IllegalArgumentException();
1827 }
1828 r.immersive = immersive;
1829
1830 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001831 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001833 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 }
1835 }
1836 }
1837
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001838 void applyUpdateLockStateLocked(ActivityRecord r) {
1839 // Modifications to the UpdateLock state are done on our handler, outside
1840 // the activity manager's locks. The new state is determined based on the
1841 // state *now* of the relevant activity record. The object is passed to
1842 // the handler solely for logging detail, not to be consulted/modified.
1843 final boolean nextState = r != null && r.immersive;
1844 mH.post(() -> {
1845 if (mUpdateLock.isHeld() != nextState) {
1846 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1847 "Applying new update lock state '" + nextState + "' for " + r);
1848 if (nextState) {
1849 mUpdateLock.acquire();
1850 } else {
1851 mUpdateLock.release();
1852 }
1853 }
1854 });
1855 }
1856
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001857 @Override
1858 public boolean isImmersive(IBinder token) {
1859 synchronized (mGlobalLock) {
1860 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1861 if (r == null) {
1862 throw new IllegalArgumentException();
1863 }
1864 return r.immersive;
1865 }
1866 }
1867
1868 @Override
1869 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001872 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001873 return (r != null) ? r.immersive : false;
1874 }
1875 }
1876
1877 @Override
1878 public void overridePendingTransition(IBinder token, String packageName,
1879 int enterAnim, int exitAnim) {
1880 synchronized (mGlobalLock) {
1881 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1882 if (self == null) {
1883 return;
1884 }
1885
1886 final long origId = Binder.clearCallingIdentity();
1887
1888 if (self.isState(
1889 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001890 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001891 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 }
1893
1894 Binder.restoreCallingIdentity(origId);
1895 }
1896 }
1897
1898 @Override
1899 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001900 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001902 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 if (r == null) {
1904 return ActivityManager.COMPAT_MODE_UNKNOWN;
1905 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001906 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 }
1908 }
1909
1910 @Override
1911 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001912 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001914 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001916 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001917 if (r == null) {
1918 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1919 return;
1920 }
1921 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001922 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 }
1924 }
1925
1926 @Override
1927 public int getLaunchedFromUid(IBinder activityToken) {
1928 ActivityRecord srec;
1929 synchronized (mGlobalLock) {
1930 srec = ActivityRecord.forTokenLocked(activityToken);
1931 }
1932 if (srec == null) {
1933 return -1;
1934 }
1935 return srec.launchedFromUid;
1936 }
1937
1938 @Override
1939 public String getLaunchedFromPackage(IBinder activityToken) {
1940 ActivityRecord srec;
1941 synchronized (mGlobalLock) {
1942 srec = ActivityRecord.forTokenLocked(activityToken);
1943 }
1944 if (srec == null) {
1945 return null;
1946 }
1947 return srec.launchedFromPackage;
1948 }
1949
1950 @Override
1951 public boolean convertFromTranslucent(IBinder token) {
1952 final long origId = Binder.clearCallingIdentity();
1953 try {
1954 synchronized (mGlobalLock) {
1955 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1956 if (r == null) {
1957 return false;
1958 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001959 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
1961 } finally {
1962 Binder.restoreCallingIdentity(origId);
1963 }
1964 }
1965
1966 @Override
1967 public boolean convertToTranslucent(IBinder token, Bundle options) {
1968 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1969 final long origId = Binder.clearCallingIdentity();
1970 try {
1971 synchronized (mGlobalLock) {
1972 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1973 if (r == null) {
1974 return false;
1975 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001976 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001977 int index = task.mActivities.lastIndexOf(r);
1978 if (index > 0) {
1979 ActivityRecord under = task.mActivities.get(index - 1);
1980 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1981 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001982 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 }
1984 } finally {
1985 Binder.restoreCallingIdentity(origId);
1986 }
1987 }
1988
1989 @Override
1990 public void notifyActivityDrawn(IBinder token) {
1991 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1992 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001993 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001995 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 }
1997 }
1998 }
1999
2000 @Override
2001 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2002 synchronized (mGlobalLock) {
2003 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2004 if (r == null) {
2005 return;
2006 }
2007 r.reportFullyDrawnLocked(restoredFromBundle);
2008 }
2009 }
2010
2011 @Override
2012 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2013 synchronized (mGlobalLock) {
2014 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2015 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2016 return stack.mDisplayId;
2017 }
2018 return DEFAULT_DISPLAY;
2019 }
2020 }
2021
2022 @Override
2023 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 long ident = Binder.clearCallingIdentity();
2026 try {
2027 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002028 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002030 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 }
2032 return null;
2033 }
2034 } finally {
2035 Binder.restoreCallingIdentity(ident);
2036 }
2037 }
2038
2039 @Override
2040 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002041 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2043 final long callingId = Binder.clearCallingIdentity();
2044 try {
2045 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002046 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 if (stack == null) {
2048 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2049 return;
2050 }
2051 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002052 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002053 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(callingId);
2058 }
2059 }
2060
2061 @Override
2062 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002069 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 if (task == null) {
2071 return;
2072 }
2073 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002074 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002084 public void restartActivityProcessIfVisible(IBinder activityToken) {
2085 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
2089 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2090 if (r == null) {
2091 return;
2092 }
2093 r.restartProcessIfVisible();
2094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(callingId);
2097 }
2098 }
2099
2100 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002102 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 synchronized (mGlobalLock) {
2104 final long ident = Binder.clearCallingIdentity();
2105 try {
2106 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2107 "remove-task");
2108 } finally {
2109 Binder.restoreCallingIdentity(ident);
2110 }
2111 }
2112 }
2113
2114 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002115 public void removeAllVisibleRecentTasks() {
2116 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2117 synchronized (mGlobalLock) {
2118 final long ident = Binder.clearCallingIdentity();
2119 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002120 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002121 } finally {
2122 Binder.restoreCallingIdentity(ident);
2123 }
2124 }
2125 }
2126
2127 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2129 synchronized (mGlobalLock) {
2130 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2131 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002132 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 }
2134 }
2135 return false;
2136 }
2137
2138 @Override
2139 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2140 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002141
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002142 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002143 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2144 if (r != null) {
2145 return r.getActivityStack().navigateUpToLocked(
2146 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002147 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002148 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 }
2150 }
2151
2152 /**
2153 * Attempts to move a task backwards in z-order (the order of activities within the task is
2154 * unchanged).
2155 *
2156 * There are several possible results of this call:
2157 * - if the task is locked, then we will show the lock toast
2158 * - if there is a task behind the provided task, then that task is made visible and resumed as
2159 * this task is moved to the back
2160 * - otherwise, if there are no other tasks in the stack:
2161 * - if this task is in the pinned stack, then we remove the stack completely, which will
2162 * have the effect of moving the task to the top or bottom of the fullscreen stack
2163 * (depending on whether it is visible)
2164 * - otherwise, we simply return home and hide this task
2165 *
2166 * @param token A reference to the activity we wish to move
2167 * @param nonRoot If false then this only works if the activity is the root
2168 * of a task; if true it will work for any activity in a task.
2169 * @return Returns true if the move completed, false if not.
2170 */
2171 @Override
2172 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002173 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 synchronized (mGlobalLock) {
2175 final long origId = Binder.clearCallingIdentity();
2176 try {
2177 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002178 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 if (task != null) {
2180 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2181 }
2182 } finally {
2183 Binder.restoreCallingIdentity(origId);
2184 }
2185 }
2186 return false;
2187 }
2188
2189 @Override
2190 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 long ident = Binder.clearCallingIdentity();
2193 Rect rect = new Rect();
2194 try {
2195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2198 if (task == null) {
2199 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2200 return rect;
2201 }
2202 if (task.getStack() != null) {
2203 // Return the bounds from window manager since it will be adjusted for various
2204 // things like the presense of a docked stack for tasks that aren't resizeable.
2205 task.getWindowContainerBounds(rect);
2206 } else {
2207 // Task isn't in window manager yet since it isn't associated with a stack.
2208 // Return the persist value from activity manager
2209 if (!task.matchParentBounds()) {
2210 rect.set(task.getBounds());
2211 } else if (task.mLastNonFullscreenBounds != null) {
2212 rect.set(task.mLastNonFullscreenBounds);
2213 }
2214 }
2215 }
2216 } finally {
2217 Binder.restoreCallingIdentity(ident);
2218 }
2219 return rect;
2220 }
2221
2222 @Override
2223 public ActivityManager.TaskDescription getTaskDescription(int id) {
2224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002225 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002227 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2229 if (tr != null) {
2230 return tr.lastTaskDescription;
2231 }
2232 }
2233 return null;
2234 }
2235
2236 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002237 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2238 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2239 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2240 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2241 return;
2242 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002244 synchronized (mGlobalLock) {
2245 final long ident = Binder.clearCallingIdentity();
2246 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002247 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002248 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 if (task == null) {
2250 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2251 return;
2252 }
2253
2254 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2255 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2256
2257 if (!task.isActivityTypeStandardOrUndefined()) {
2258 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2259 + " non-standard task " + taskId + " to windowing mode="
2260 + windowingMode);
2261 }
2262
2263 final ActivityStack stack = task.getStack();
2264 if (toTop) {
2265 stack.moveToFront("setTaskWindowingMode", task);
2266 }
2267 stack.setWindowingMode(windowingMode);
2268 } finally {
2269 Binder.restoreCallingIdentity(ident);
2270 }
2271 }
2272 }
2273
2274 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002276 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002277 ActivityRecord r = getCallingRecordLocked(token);
2278 return r != null ? r.info.packageName : null;
2279 }
2280 }
2281
2282 @Override
2283 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285 ActivityRecord r = getCallingRecordLocked(token);
2286 return r != null ? r.intent.getComponent() : null;
2287 }
2288 }
2289
2290 private ActivityRecord getCallingRecordLocked(IBinder token) {
2291 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2292 if (r == null) {
2293 return null;
2294 }
2295 return r.resultTo;
2296 }
2297
2298 @Override
2299 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002300 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301
2302 synchronized (mGlobalLock) {
2303 final long origId = Binder.clearCallingIdentity();
2304 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002305 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 } finally {
2307 Binder.restoreCallingIdentity(origId);
2308 }
2309 }
2310 }
2311
Mark Renouf446251d2019-04-26 10:22:41 -04002312 @Override
2313 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2314 synchronized (mGlobalLock) {
2315 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2316 if (r == null) {
2317 return;
2318 }
2319 ActivityStack stack = r.getActivityStack();
2320 if (stack != null && stack.isSingleTaskInstance()) {
2321 // Single-task stacks are used for activities which are presented in floating
2322 // windows above full screen activities. Instead of directly finishing the
2323 // task, a task change listener is used to notify SystemUI so the action can be
2324 // handled specially.
2325 final TaskRecord task = r.getTaskRecord();
2326 mTaskChangeNotificationController
2327 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2328 } else {
2329 try {
2330 callback.requestFinish();
2331 } catch (RemoteException e) {
2332 Slog.e(TAG, "Failed to invoke request finish callback", e);
2333 }
2334 }
2335 }
2336 }
2337
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 /**
2339 * TODO: Add mController hook
2340 */
2341 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002342 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2343 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345
2346 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2347 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002348 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2349 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 }
2351 }
2352
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2354 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002356
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 final int callingPid = Binder.getCallingPid();
2358 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002359 if (!isSameApp(callingUid, callingPackage)) {
2360 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2361 + Binder.getCallingPid() + " as package " + callingPackage;
2362 Slog.w(TAG, msg);
2363 throw new SecurityException(msg);
2364 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 SafeActivityOptions.abort(options);
2367 return;
2368 }
2369 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 WindowProcessController callerApp = null;
2371 if (appThread != null) {
2372 callerApp = getProcessController(appThread);
2373 }
2374 final ActivityStarter starter = getActivityStartController().obtainStarter(
2375 null /* intent */, "moveTaskToFront");
2376 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2377 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002378 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 return;
2380 }
2381 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002383 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 if (task == null) {
2385 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002386 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 return;
2388 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002389 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002391 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 return;
2393 }
2394 ActivityOptions realOptions = options != null
2395 ? options.getOptions(mStackSupervisor)
2396 : null;
2397 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2398 false /* forceNonResizable */);
2399
2400 final ActivityRecord topActivity = task.getTopActivity();
2401 if (topActivity != null) {
2402
2403 // We are reshowing a task, use a starting window to hide the initial draw delay
2404 // so the transition can start earlier.
2405 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2406 true /* taskSwitch */, fromRecents);
2407 }
2408 } finally {
2409 Binder.restoreCallingIdentity(origId);
2410 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 }
2412
Ricky Waiaca8a772019-04-04 16:01:06 +01002413 /**
2414 * Return true if callingUid is system, or packageName belongs to that callingUid.
2415 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002416 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002417 try {
2418 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2419 if (packageName == null) {
2420 return false;
2421 }
2422 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2423 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2424 UserHandle.getUserId(callingUid));
2425 return UserHandle.isSameApp(callingUid, uid);
2426 }
2427 } catch (RemoteException e) {
2428 // Should not happen
2429 }
2430 return true;
2431 }
2432
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002433 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2434 int callingPid, int callingUid, String name) {
2435 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2436 return true;
2437 }
2438
2439 if (getRecentTasks().isCallerRecents(sourceUid)) {
2440 return true;
2441 }
2442
2443 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2444 if (perm == PackageManager.PERMISSION_GRANTED) {
2445 return true;
2446 }
2447 if (checkAllowAppSwitchUid(sourceUid)) {
2448 return true;
2449 }
2450
2451 // If the actual IPC caller is different from the logical source, then
2452 // also see if they are allowed to control app switches.
2453 if (callingUid != -1 && callingUid != sourceUid) {
2454 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2455 if (perm == PackageManager.PERMISSION_GRANTED) {
2456 return true;
2457 }
2458 if (checkAllowAppSwitchUid(callingUid)) {
2459 return true;
2460 }
2461 }
2462
2463 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2464 return false;
2465 }
2466
2467 private boolean checkAllowAppSwitchUid(int uid) {
2468 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2469 if (types != null) {
2470 for (int i = types.size() - 1; i >= 0; i--) {
2471 if (types.valueAt(i).intValue() == uid) {
2472 return true;
2473 }
2474 }
2475 }
2476 return false;
2477 }
2478
2479 @Override
2480 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2481 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2482 "setActivityController()");
2483 synchronized (mGlobalLock) {
2484 mController = controller;
2485 mControllerIsAMonkey = imAMonkey;
2486 Watchdog.getInstance().setActivityController(controller);
2487 }
2488 }
2489
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002490 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002491 synchronized (mGlobalLock) {
2492 return mController != null && mControllerIsAMonkey;
2493 }
2494 }
2495
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002496 @Override
2497 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2498 synchronized (mGlobalLock) {
2499 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2500 }
2501 }
2502
2503 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2505 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2506 }
2507
2508 @Override
2509 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2510 @WindowConfiguration.ActivityType int ignoreActivityType,
2511 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2512 final int callingUid = Binder.getCallingUid();
2513 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2514
2515 synchronized (mGlobalLock) {
2516 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2517
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002518 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002520 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 ignoreWindowingMode, callingUid, allowed);
2522 }
2523
2524 return list;
2525 }
2526
2527 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002528 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2529 synchronized (mGlobalLock) {
2530 final long origId = Binder.clearCallingIdentity();
2531 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2532 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002533 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 }
2535 Binder.restoreCallingIdentity(origId);
2536 }
2537 }
2538
2539 @Override
2540 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002541 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542 ActivityStack stack = ActivityRecord.getStackLocked(token);
2543 if (stack != null) {
2544 return stack.willActivityBeVisibleLocked(token);
2545 }
2546 return false;
2547 }
2548 }
2549
2550 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002552 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 synchronized (mGlobalLock) {
2554 final long ident = Binder.clearCallingIdentity();
2555 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002556 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002557 if (task == null) {
2558 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2559 return;
2560 }
2561
2562 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2563 + " to stackId=" + stackId + " toTop=" + toTop);
2564
Wale Ogunwaled32da472018-11-16 07:19:28 -08002565 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002566 if (stack == null) {
2567 throw new IllegalStateException(
2568 "moveTaskToStack: No stack for stackId=" + stackId);
2569 }
2570 if (!stack.isActivityTypeStandardOrUndefined()) {
2571 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2572 + taskId + " to stack " + stackId);
2573 }
2574 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002575 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002576 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2577 }
2578 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2579 "moveTaskToStack");
2580 } finally {
2581 Binder.restoreCallingIdentity(ident);
2582 }
2583 }
2584 }
2585
2586 @Override
2587 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2588 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002589 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590
2591 final long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
2594 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002595 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 if (stack == null) {
2597 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2598 return;
2599 }
2600 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2601 throw new IllegalArgumentException("Stack: " + stackId
2602 + " doesn't support animated resize.");
2603 }
2604 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2605 animationDuration, false /* fromFullscreen */);
2606 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002607 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002608 if (stack == null) {
2609 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2610 return;
2611 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002612 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2614 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2615 }
2616 }
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 }
2913 synchronized (this) {
2914 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 Ogunwale8b19de92018-11-29 19:58:26 -08003034 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3035 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,
3061 pae.activity.getTaskRecord().taskId);
3062 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 }
3157 task.lastTaskDescription.copyFrom(description);
3158
3159 // TODO: Send the thumbnail to WM to store it.
3160
3161 return task.taskId;
3162 }
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 Ogunwalea6191b42018-05-09 07:41:32 -07003323 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3325 final ActivityOptions activityOptions = safeOptions != null
3326 ? safeOptions.getOptions(mStackSupervisor)
3327 : null;
3328 if (activityOptions == null
3329 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3330 || activityOptions.getCustomInPlaceResId() == 0) {
3331 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3332 "with valid animation");
3333 }
lumark588a3e82018-07-20 18:53:54 +08003334 // Get top display of front most application.
3335 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3336 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003337 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3338 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3339 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003340 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003341 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003342 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 }
3344
3345 @Override
3346 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003347 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 synchronized (mGlobalLock) {
3349 final long ident = Binder.clearCallingIdentity();
3350 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003351 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 if (stack == null) {
3353 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3354 return;
3355 }
3356 if (!stack.isActivityTypeStandardOrUndefined()) {
3357 throw new IllegalArgumentException(
3358 "Removing non-standard stack is not allowed.");
3359 }
3360 mStackSupervisor.removeStack(stack);
3361 } finally {
3362 Binder.restoreCallingIdentity(ident);
3363 }
3364 }
3365 }
3366
3367 @Override
3368 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370
3371 synchronized (mGlobalLock) {
3372 final long ident = Binder.clearCallingIdentity();
3373 try {
3374 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3375 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003376 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003377 } finally {
3378 Binder.restoreCallingIdentity(ident);
3379 }
3380 }
3381 }
3382
3383 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003384 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 synchronized (mGlobalLock) {
3386 long ident = Binder.clearCallingIdentity();
3387 try {
3388 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3389 if (r == null) {
3390 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003391 "toggleFreeformWindowingMode: No activity record matching token="
3392 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 }
3394
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003395 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003396 if (stack == null) {
3397 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3398 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 }
3400
Yunfan Chend967af82019-01-17 18:30:18 +09003401 if (!stack.inFreeformWindowingMode()
3402 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3403 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3404 + "toggle between fullscreen and freeform.");
3405 }
3406
3407 if (stack.inFreeformWindowingMode()) {
3408 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003409 } else if (stack.getParent().inFreeformWindowingMode()) {
3410 // If the window is on a freeform display, set it to undefined. It will be
3411 // resolved to freeform and it can adjust windowing mode when the display mode
3412 // changes in runtime.
3413 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003414 } else {
3415 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3416 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417 } finally {
3418 Binder.restoreCallingIdentity(ident);
3419 }
3420 }
3421 }
3422
3423 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3424 @Override
3425 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003426 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003428 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003429 }
3430
3431 /** Unregister a task stack listener so that it stops receiving callbacks. */
3432 @Override
3433 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003436 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 }
3438
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003439 @Override
3440 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3441 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3442 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3443 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3444 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3445 }
3446
3447 @Override
3448 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3449 IBinder activityToken, int flags) {
3450 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3451 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3452 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3453 }
3454
3455 @Override
3456 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3457 Bundle args) {
3458 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3459 true /* focused */, true /* newSessionId */, userHandle, args,
3460 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3461 }
3462
3463 @Override
3464 public Bundle getAssistContextExtras(int requestType) {
3465 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3466 null, null, true /* focused */, true /* newSessionId */,
3467 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3468 if (pae == null) {
3469 return null;
3470 }
3471 synchronized (pae) {
3472 while (!pae.haveResult) {
3473 try {
3474 pae.wait();
3475 } catch (InterruptedException e) {
3476 }
3477 }
3478 }
3479 synchronized (mGlobalLock) {
3480 buildAssistBundleLocked(pae, pae.result);
3481 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003482 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003483 }
3484 return pae.extras;
3485 }
3486
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003487 /**
3488 * Binder IPC calls go through the public entry point.
3489 * This can be called with or without the global lock held.
3490 */
3491 private static int checkCallingPermission(String permission) {
3492 return checkPermission(
3493 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3494 }
3495
3496 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003497 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003498 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3499 mAmInternal.enforceCallingPermission(permission, func);
3500 }
3501 }
3502
3503 @VisibleForTesting
3504 int checkGetTasksPermission(String permission, int pid, int uid) {
3505 return checkPermission(permission, pid, uid);
3506 }
3507
3508 static int checkPermission(String permission, int pid, int uid) {
3509 if (permission == null) {
3510 return PackageManager.PERMISSION_DENIED;
3511 }
3512 return checkComponentPermission(permission, pid, uid, -1, true);
3513 }
3514
Wale Ogunwale214f3482018-10-04 11:00:47 -07003515 public static int checkComponentPermission(String permission, int pid, int uid,
3516 int owningUid, boolean exported) {
3517 return ActivityManagerService.checkComponentPermission(
3518 permission, pid, uid, owningUid, exported);
3519 }
3520
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003521 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3522 if (getRecentTasks().isCallerRecents(callingUid)) {
3523 // Always allow the recents component to get tasks
3524 return true;
3525 }
3526
3527 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3528 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3529 if (!allowed) {
3530 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3531 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3532 // Temporary compatibility: some existing apps on the system image may
3533 // still be requesting the old permission and not switched to the new
3534 // one; if so, we'll still allow them full access. This means we need
3535 // to see if they are holding the old permission and are a system app.
3536 try {
3537 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3538 allowed = true;
3539 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3540 + " is using old GET_TASKS but privileged; allowing");
3541 }
3542 } catch (RemoteException e) {
3543 }
3544 }
3545 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3546 + " does not hold REAL_GET_TASKS; limiting output");
3547 }
3548 return allowed;
3549 }
3550
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3552 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3553 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3554 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003555 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003556 "enqueueAssistContext()");
3557
3558 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003559 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 if (activity == null) {
3561 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3562 return null;
3563 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003564 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003565 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3566 return null;
3567 }
3568 if (focused) {
3569 if (activityToken != null) {
3570 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3571 if (activity != caller) {
3572 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3573 + " is not current top " + activity);
3574 return null;
3575 }
3576 }
3577 } else {
3578 activity = ActivityRecord.forTokenLocked(activityToken);
3579 if (activity == null) {
3580 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3581 + " couldn't be found");
3582 return null;
3583 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003584 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003585 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3586 return null;
3587 }
3588 }
3589
3590 PendingAssistExtras pae;
3591 Bundle extras = new Bundle();
3592 if (args != null) {
3593 extras.putAll(args);
3594 }
3595 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003596 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003597
3598 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3599 userHandle);
3600 pae.isHome = activity.isActivityTypeHome();
3601
3602 // Increment the sessionId if necessary
3603 if (newSessionId) {
3604 mViSessionId++;
3605 }
3606 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003607 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3608 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003610 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 } catch (RemoteException e) {
3612 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3613 return null;
3614 }
3615 return pae;
3616 }
3617 }
3618
3619 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3620 if (result != null) {
3621 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3622 }
3623 if (pae.hint != null) {
3624 pae.extras.putBoolean(pae.hint, true);
3625 }
3626 }
3627
3628 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3629 IAssistDataReceiver receiver;
3630 synchronized (mGlobalLock) {
3631 mPendingAssistExtras.remove(pae);
3632 receiver = pae.receiver;
3633 }
3634 if (receiver != null) {
3635 // Caller wants result sent back to them.
3636 Bundle sendBundle = new Bundle();
3637 // At least return the receiver extras
3638 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3639 try {
3640 pae.receiver.onHandleAssistData(sendBundle);
3641 } catch (RemoteException e) {
3642 }
3643 }
3644 }
3645
3646 public class PendingAssistExtras extends Binder implements Runnable {
3647 public final ActivityRecord activity;
3648 public boolean isHome;
3649 public final Bundle extras;
3650 public final Intent intent;
3651 public final String hint;
3652 public final IAssistDataReceiver receiver;
3653 public final int userHandle;
3654 public boolean haveResult = false;
3655 public Bundle result = null;
3656 public AssistStructure structure = null;
3657 public AssistContent content = null;
3658 public Bundle receiverExtras;
3659
3660 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3661 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3662 int _userHandle) {
3663 activity = _activity;
3664 extras = _extras;
3665 intent = _intent;
3666 hint = _hint;
3667 receiver = _receiver;
3668 receiverExtras = _receiverExtras;
3669 userHandle = _userHandle;
3670 }
3671
3672 @Override
3673 public void run() {
3674 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3675 synchronized (this) {
3676 haveResult = true;
3677 notifyAll();
3678 }
3679 pendingAssistExtrasTimedOut(this);
3680 }
3681 }
3682
3683 @Override
3684 public boolean isAssistDataAllowedOnCurrentActivity() {
3685 int userId;
3686 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003687 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003688 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3689 return false;
3690 }
3691
3692 final ActivityRecord activity = focusedStack.getTopActivity();
3693 if (activity == null) {
3694 return false;
3695 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003696 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 }
3698 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3699 }
3700
3701 @Override
3702 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3703 long ident = Binder.clearCallingIdentity();
3704 try {
3705 synchronized (mGlobalLock) {
3706 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003707 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 if (top != caller) {
3709 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3710 + " is not current top " + top);
3711 return false;
3712 }
3713 if (!top.nowVisible) {
3714 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3715 + " is not visible");
3716 return false;
3717 }
3718 }
3719 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3720 token);
3721 } finally {
3722 Binder.restoreCallingIdentity(ident);
3723 }
3724 }
3725
3726 @Override
3727 public boolean isRootVoiceInteraction(IBinder token) {
3728 synchronized (mGlobalLock) {
3729 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3730 if (r == null) {
3731 return false;
3732 }
3733 return r.rootVoiceInteraction;
3734 }
3735 }
3736
Wale Ogunwalef6733932018-06-27 05:14:34 -07003737 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3738 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3739 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3740 if (activityToCallback == null) return;
3741 activityToCallback.setVoiceSessionLocked(voiceSession);
3742
3743 // Inform the activity
3744 try {
3745 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3746 voiceInteractor);
3747 long token = Binder.clearCallingIdentity();
3748 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003749 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003750 } finally {
3751 Binder.restoreCallingIdentity(token);
3752 }
3753 // TODO: VI Should we cache the activity so that it's easier to find later
3754 // rather than scan through all the stacks and activities?
3755 } catch (RemoteException re) {
3756 activityToCallback.clearVoiceSessionLocked();
3757 // TODO: VI Should this terminate the voice session?
3758 }
3759 }
3760
3761 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3762 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3763 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3764 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3765 boolean wasRunningVoice = mRunningVoice != null;
3766 mRunningVoice = session;
3767 if (!wasRunningVoice) {
3768 mVoiceWakeLock.acquire();
3769 updateSleepIfNeededLocked();
3770 }
3771 }
3772 }
3773
3774 void finishRunningVoiceLocked() {
3775 if (mRunningVoice != null) {
3776 mRunningVoice = null;
3777 mVoiceWakeLock.release();
3778 updateSleepIfNeededLocked();
3779 }
3780 }
3781
3782 @Override
3783 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3784 synchronized (mGlobalLock) {
3785 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3786 if (keepAwake) {
3787 mVoiceWakeLock.acquire();
3788 } else {
3789 mVoiceWakeLock.release();
3790 }
3791 }
3792 }
3793 }
3794
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 @Override
3796 public ComponentName getActivityClassForToken(IBinder token) {
3797 synchronized (mGlobalLock) {
3798 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3799 if (r == null) {
3800 return null;
3801 }
3802 return r.intent.getComponent();
3803 }
3804 }
3805
3806 @Override
3807 public String getPackageForToken(IBinder token) {
3808 synchronized (mGlobalLock) {
3809 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3810 if (r == null) {
3811 return null;
3812 }
3813 return r.packageName;
3814 }
3815 }
3816
3817 @Override
3818 public void showLockTaskEscapeMessage(IBinder token) {
3819 synchronized (mGlobalLock) {
3820 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3821 if (r == null) {
3822 return;
3823 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003824 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003825 }
3826 }
3827
3828 @Override
3829 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003830 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 final long token = Binder.clearCallingIdentity();
3832 try {
3833 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003834 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003835 }
3836 } finally {
3837 Binder.restoreCallingIdentity(token);
3838 }
3839 }
3840
3841 /**
3842 * Try to place task to provided position. The final position might be different depending on
3843 * current user and stacks state. The task will be moved to target stack if it's currently in
3844 * different stack.
3845 */
3846 @Override
3847 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003848 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003849 synchronized (mGlobalLock) {
3850 long ident = Binder.clearCallingIdentity();
3851 try {
3852 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3853 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003854 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855 if (task == null) {
3856 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3857 + taskId);
3858 }
3859
Wale Ogunwaled32da472018-11-16 07:19:28 -08003860 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003861
3862 if (stack == null) {
3863 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3864 + stackId);
3865 }
3866 if (!stack.isActivityTypeStandardOrUndefined()) {
3867 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3868 + " the position of task " + taskId + " in/to non-standard stack");
3869 }
3870
3871 // TODO: Have the callers of this API call a separate reparent method if that is
3872 // what they intended to do vs. having this method also do reparenting.
3873 if (task.getStack() == stack) {
3874 // Change position in current stack.
3875 stack.positionChildAt(task, position);
3876 } else {
3877 // Reparent to new stack.
3878 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3879 !DEFER_RESUME, "positionTaskInStack");
3880 }
3881 } finally {
3882 Binder.restoreCallingIdentity(ident);
3883 }
3884 }
3885 }
3886
3887 @Override
3888 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3889 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3890 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003891 + Arrays.toString(horizontalSizeConfiguration) + " "
3892 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 synchronized (mGlobalLock) {
3894 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3895 if (record == null) {
3896 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3897 + "found for: " + token);
3898 }
3899 record.setSizeConfigurations(horizontalSizeConfiguration,
3900 verticalSizeConfigurations, smallestSizeConfigurations);
3901 }
3902 }
3903
3904 /**
3905 * Dismisses split-screen multi-window mode.
3906 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3907 */
3908 @Override
3909 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003910 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3912 final long ident = Binder.clearCallingIdentity();
3913 try {
3914 synchronized (mGlobalLock) {
3915 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003916 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003917 if (stack == null) {
3918 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3919 return;
3920 }
3921
3922 if (toTop) {
3923 // Caller wants the current split-screen primary stack to be the top stack after
3924 // it goes fullscreen, so move it to the front.
3925 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003926 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003927 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003928 // stack after it goes fullscreen, so we move the focus to the top-most
3929 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3931 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3932 if (otherStack != null) {
3933 otherStack.moveToFront("dismissSplitScreenMode_other");
3934 }
3935 }
3936
Evan Rosky10475742018-09-05 19:02:48 -07003937 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 }
3939 } finally {
3940 Binder.restoreCallingIdentity(ident);
3941 }
3942 }
3943
3944 /**
3945 * Dismisses Pip
3946 * @param animate True if the dismissal should be animated.
3947 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3948 * default animation duration should be used.
3949 */
3950 @Override
3951 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003952 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 final long ident = Binder.clearCallingIdentity();
3954 try {
3955 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003956 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003957 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 if (stack == null) {
3959 Slog.w(TAG, "dismissPip: pinned stack not found.");
3960 return;
3961 }
3962 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3963 throw new IllegalArgumentException("Stack: " + stack
3964 + " doesn't support animated resize.");
3965 }
3966 if (animate) {
3967 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3968 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3969 } else {
3970 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3971 }
3972 }
3973 } finally {
3974 Binder.restoreCallingIdentity(ident);
3975 }
3976 }
3977
3978 @Override
3979 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003980 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003981 synchronized (mGlobalLock) {
3982 mSuppressResizeConfigChanges = suppress;
3983 }
3984 }
3985
3986 /**
3987 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3988 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3989 * activity and clearing the task at the same time.
3990 */
3991 @Override
3992 // TODO: API should just be about changing windowing modes...
3993 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003994 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 "moveTasksToFullscreenStack()");
3996 synchronized (mGlobalLock) {
3997 final long origId = Binder.clearCallingIdentity();
3998 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003999 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 if (stack != null){
4001 if (!stack.isActivityTypeStandardOrUndefined()) {
4002 throw new IllegalArgumentException(
4003 "You can't move tasks from non-standard stacks.");
4004 }
4005 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4006 }
4007 } finally {
4008 Binder.restoreCallingIdentity(origId);
4009 }
4010 }
4011 }
4012
4013 /**
4014 * Moves the top activity in the input stackId to the pinned stack.
4015 *
4016 * @param stackId Id of stack to move the top activity to pinned stack.
4017 * @param bounds Bounds to use for pinned stack.
4018 *
4019 * @return True if the top activity of the input stack was successfully moved to the pinned
4020 * stack.
4021 */
4022 @Override
4023 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004025 "moveTopActivityToPinnedStack()");
4026 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004027 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4029 + "Device doesn't support picture-in-picture mode");
4030 }
4031
4032 long ident = Binder.clearCallingIdentity();
4033 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004034 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 } finally {
4036 Binder.restoreCallingIdentity(ident);
4037 }
4038 }
4039 }
4040
4041 @Override
4042 public boolean isInMultiWindowMode(IBinder token) {
4043 final long origId = Binder.clearCallingIdentity();
4044 try {
4045 synchronized (mGlobalLock) {
4046 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4047 if (r == null) {
4048 return false;
4049 }
4050 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4051 return r.inMultiWindowMode();
4052 }
4053 } finally {
4054 Binder.restoreCallingIdentity(origId);
4055 }
4056 }
4057
4058 @Override
4059 public boolean isInPictureInPictureMode(IBinder token) {
4060 final long origId = Binder.clearCallingIdentity();
4061 try {
4062 synchronized (mGlobalLock) {
4063 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4064 }
4065 } finally {
4066 Binder.restoreCallingIdentity(origId);
4067 }
4068 }
4069
4070 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004071 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4072 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 return false;
4074 }
4075
4076 // If we are animating to fullscreen then we have already dispatched the PIP mode
4077 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004078 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4079 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 }
4081
4082 @Override
4083 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4084 final long origId = Binder.clearCallingIdentity();
4085 try {
4086 synchronized (mGlobalLock) {
4087 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4088 "enterPictureInPictureMode", token, params);
4089
4090 // If the activity is already in picture in picture mode, then just return early
4091 if (isInPictureInPictureMode(r)) {
4092 return true;
4093 }
4094
4095 // Activity supports picture-in-picture, now check that we can enter PiP at this
4096 // point, if it is
4097 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4098 false /* beforeStopping */)) {
4099 return false;
4100 }
4101
4102 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004103 synchronized (mGlobalLock) {
4104 // Only update the saved args from the args that are set
4105 r.pictureInPictureArgs.copyOnlySet(params);
4106 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4107 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4108 // Adjust the source bounds by the insets for the transition down
4109 final Rect sourceBounds = new Rect(
4110 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004111 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004112 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004113 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004114 stack.setPictureInPictureAspectRatio(aspectRatio);
4115 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004116 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4117 r.info.applicationInfo.uid, r.shortComponentName,
4118 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004119 logPictureInPictureArgs(params);
4120 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 };
4122
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004123 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004124 // If the keyguard is showing or occluded, then try and dismiss it before
4125 // entering picture-in-picture (this will prompt the user to authenticate if the
4126 // device is currently locked).
4127 dismissKeyguard(token, new KeyguardDismissCallback() {
4128 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004129 public void onDismissSucceeded() {
4130 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004131 }
4132 }, null /* message */);
4133 } else {
4134 // Enter picture in picture immediately otherwise
4135 enterPipRunnable.run();
4136 }
4137 return true;
4138 }
4139 } finally {
4140 Binder.restoreCallingIdentity(origId);
4141 }
4142 }
4143
4144 @Override
4145 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4146 final long origId = Binder.clearCallingIdentity();
4147 try {
4148 synchronized (mGlobalLock) {
4149 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4150 "setPictureInPictureParams", token, params);
4151
4152 // Only update the saved args from the args that are set
4153 r.pictureInPictureArgs.copyOnlySet(params);
4154 if (r.inPinnedWindowingMode()) {
4155 // If the activity is already in picture-in-picture, update the pinned stack now
4156 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4157 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004158 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 if (!stack.isAnimatingBoundsToFullscreen()) {
4160 stack.setPictureInPictureAspectRatio(
4161 r.pictureInPictureArgs.getAspectRatio());
4162 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4163 }
4164 }
4165 logPictureInPictureArgs(params);
4166 }
4167 } finally {
4168 Binder.restoreCallingIdentity(origId);
4169 }
4170 }
4171
4172 @Override
4173 public int getMaxNumPictureInPictureActions(IBinder token) {
4174 // Currently, this is a static constant, but later, we may change this to be dependent on
4175 // the context of the activity
4176 return 3;
4177 }
4178
4179 private void logPictureInPictureArgs(PictureInPictureParams params) {
4180 if (params.hasSetActions()) {
4181 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4182 params.getActions().size());
4183 }
4184 if (params.hasSetAspectRatio()) {
4185 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4186 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4187 MetricsLogger.action(lm);
4188 }
4189 }
4190
4191 /**
4192 * Checks the state of the system and the activity associated with the given {@param token} to
4193 * verify that picture-in-picture is supported for that activity.
4194 *
4195 * @return the activity record for the given {@param token} if all the checks pass.
4196 */
4197 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4198 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004199 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 throw new IllegalStateException(caller
4201 + ": Device doesn't support picture-in-picture mode.");
4202 }
4203
4204 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4205 if (r == null) {
4206 throw new IllegalStateException(caller
4207 + ": Can't find activity for token=" + token);
4208 }
4209
4210 if (!r.supportsPictureInPicture()) {
4211 throw new IllegalStateException(caller
4212 + ": Current activity does not support picture-in-picture.");
4213 }
4214
4215 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004216 && !mWindowManager.isValidPictureInPictureAspectRatio(
4217 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 final float minAspectRatio = mContext.getResources().getFloat(
4219 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4220 final float maxAspectRatio = mContext.getResources().getFloat(
4221 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4222 throw new IllegalArgumentException(String.format(caller
4223 + ": Aspect ratio is too extreme (must be between %f and %f).",
4224 minAspectRatio, maxAspectRatio));
4225 }
4226
4227 // Truncate the number of actions if necessary
4228 params.truncateActions(getMaxNumPictureInPictureActions(token));
4229
4230 return r;
4231 }
4232
4233 @Override
4234 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004236 synchronized (mGlobalLock) {
4237 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4238 if (r == null) {
4239 throw new IllegalArgumentException("Activity does not exist; token="
4240 + activityToken);
4241 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004242 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 }
4244 }
4245
4246 @Override
4247 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4248 Rect tempDockedTaskInsetBounds,
4249 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 long ident = Binder.clearCallingIdentity();
4252 try {
4253 synchronized (mGlobalLock) {
4254 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4255 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4256 PRESERVE_WINDOWS);
4257 }
4258 } finally {
4259 Binder.restoreCallingIdentity(ident);
4260 }
4261 }
4262
4263 @Override
4264 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 final long ident = Binder.clearCallingIdentity();
4267 try {
4268 synchronized (mGlobalLock) {
4269 mStackSupervisor.setSplitScreenResizing(resizing);
4270 }
4271 } finally {
4272 Binder.restoreCallingIdentity(ident);
4273 }
4274 }
4275
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 /**
4277 * Check that we have the features required for VR-related API calls, and throw an exception if
4278 * not.
4279 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004280 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004281 if (!mContext.getPackageManager().hasSystemFeature(
4282 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4283 throw new UnsupportedOperationException("VR mode not supported on this device!");
4284 }
4285 }
4286
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004287 @Override
4288 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004289 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004290
4291 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4292
4293 ActivityRecord r;
4294 synchronized (mGlobalLock) {
4295 r = ActivityRecord.isInStackLocked(token);
4296 }
4297
4298 if (r == null) {
4299 throw new IllegalArgumentException();
4300 }
4301
4302 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004303 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004304 VrManagerInternal.NO_ERROR) {
4305 return err;
4306 }
4307
4308 // Clear the binder calling uid since this path may call moveToTask().
4309 final long callingId = Binder.clearCallingIdentity();
4310 try {
4311 synchronized (mGlobalLock) {
4312 r.requestedVrComponent = (enabled) ? packageName : null;
4313
4314 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004315 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004316 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004317 }
4318 return 0;
4319 }
4320 } finally {
4321 Binder.restoreCallingIdentity(callingId);
4322 }
4323 }
4324
4325 @Override
4326 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4327 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4328 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004329 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004330 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4331 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4332 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004333 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 || activity.voiceSession != null) {
4335 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4336 return;
4337 }
4338 if (activity.pendingVoiceInteractionStart) {
4339 Slog.w(TAG, "Pending start of voice interaction already.");
4340 return;
4341 }
4342 activity.pendingVoiceInteractionStart = true;
4343 }
4344 LocalServices.getService(VoiceInteractionManagerInternal.class)
4345 .startLocalVoiceInteraction(callingActivity, options);
4346 }
4347
4348 @Override
4349 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4350 LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .stopLocalVoiceInteraction(callingActivity);
4352 }
4353
4354 @Override
4355 public boolean supportsLocalVoiceInteraction() {
4356 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4357 .supportsLocalVoiceInteraction();
4358 }
4359
4360 /** Notifies all listeners when the pinned stack animation starts. */
4361 @Override
4362 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004363 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 }
4365
4366 /** Notifies all listeners when the pinned stack animation ends. */
4367 @Override
4368 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004369 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371
4372 @Override
4373 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 final long ident = Binder.clearCallingIdentity();
4376 try {
4377 synchronized (mGlobalLock) {
4378 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4379 }
4380 } finally {
4381 Binder.restoreCallingIdentity(ident);
4382 }
4383 }
4384
4385 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388
4389 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004392 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 }
4394
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004395 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004396 final Message msg = PooledLambda.obtainMessage(
4397 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4398 DEFAULT_DISPLAY);
4399 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004400 }
4401
4402 final long origId = Binder.clearCallingIdentity();
4403 try {
4404 if (values != null) {
4405 Settings.System.clearConfiguration(values);
4406 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004407 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 UserHandle.USER_NULL, false /* deferResume */,
4409 mTmpUpdateConfigurationResult);
4410 return mTmpUpdateConfigurationResult.changes != 0;
4411 } finally {
4412 Binder.restoreCallingIdentity(origId);
4413 }
4414 }
4415 }
4416
4417 @Override
4418 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4419 CharSequence message) {
4420 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004421 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4423 }
4424 final long callingId = Binder.clearCallingIdentity();
4425 try {
4426 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004427 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 }
4429 } finally {
4430 Binder.restoreCallingIdentity(callingId);
4431 }
4432 }
4433
4434 @Override
4435 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004436 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437 "cancelTaskWindowTransition()");
4438 final long ident = Binder.clearCallingIdentity();
4439 try {
4440 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004441 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 MATCH_TASK_IN_STACKS_ONLY);
4443 if (task == null) {
4444 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4445 return;
4446 }
4447 task.cancelWindowTransition();
4448 }
4449 } finally {
4450 Binder.restoreCallingIdentity(ident);
4451 }
4452 }
4453
4454 @Override
4455 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 final long ident = Binder.clearCallingIdentity();
4458 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004459 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004460 } finally {
4461 Binder.restoreCallingIdentity(ident);
4462 }
4463 }
4464
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004465 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4466 boolean restoreFromDisk) {
4467 final TaskRecord task;
4468 synchronized (mGlobalLock) {
4469 task = mRootActivityContainer.anyTaskForId(taskId,
4470 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4471 if (task == null) {
4472 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4473 return null;
4474 }
4475 }
4476 // Don't call this while holding the lock as this operation might hit the disk.
4477 return task.getSnapshot(reducedResolution, restoreFromDisk);
4478 }
4479
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 @Override
4481 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4482 synchronized (mGlobalLock) {
4483 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4484 if (r == null) {
4485 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4486 + token);
4487 return;
4488 }
4489 final long origId = Binder.clearCallingIdentity();
4490 try {
4491 r.setDisablePreviewScreenshots(disable);
4492 } finally {
4493 Binder.restoreCallingIdentity(origId);
4494 }
4495 }
4496 }
4497
4498 /** Return the user id of the last resumed activity. */
4499 @Override
4500 public @UserIdInt
4501 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004502 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4504 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004505 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004506 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004508 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004509 }
4510 }
4511
4512 @Override
4513 public void updateLockTaskFeatures(int userId, int flags) {
4514 final int callingUid = Binder.getCallingUid();
4515 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004516 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 "updateLockTaskFeatures()");
4518 }
4519 synchronized (mGlobalLock) {
4520 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4521 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004522 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 }
4524 }
4525
4526 @Override
4527 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
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.setShowWhenLocked(showWhenLocked);
4536 } finally {
4537 Binder.restoreCallingIdentity(origId);
4538 }
4539 }
4540 }
4541
4542 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004543 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
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.setInheritShowWhenLocked(inheritShowWhenLocked);
4552 } finally {
4553 Binder.restoreCallingIdentity(origId);
4554 }
4555 }
4556 }
4557
4558 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004559 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4560 synchronized (mGlobalLock) {
4561 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4562 if (r == null) {
4563 return;
4564 }
4565 final long origId = Binder.clearCallingIdentity();
4566 try {
4567 r.setTurnScreenOn(turnScreenOn);
4568 } finally {
4569 Binder.restoreCallingIdentity(origId);
4570 }
4571 }
4572 }
4573
4574 @Override
4575 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004576 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004577 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004578 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004579 synchronized (mGlobalLock) {
4580 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4581 if (r == null) {
4582 return;
4583 }
4584 final long origId = Binder.clearCallingIdentity();
4585 try {
4586 r.registerRemoteAnimations(definition);
4587 } finally {
4588 Binder.restoreCallingIdentity(origId);
4589 }
4590 }
4591 }
4592
4593 @Override
4594 public void registerRemoteAnimationForNextActivityStart(String packageName,
4595 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004596 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004598 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004599 synchronized (mGlobalLock) {
4600 final long origId = Binder.clearCallingIdentity();
4601 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004602 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004603 packageName, adapter);
4604 } finally {
4605 Binder.restoreCallingIdentity(origId);
4606 }
4607 }
4608 }
4609
Evan Rosky966759f2019-01-15 10:33:58 -08004610 @Override
4611 public void registerRemoteAnimationsForDisplay(int displayId,
4612 RemoteAnimationDefinition definition) {
4613 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4614 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004615 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004616 synchronized (mGlobalLock) {
4617 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4618 if (display == null) {
4619 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4620 return;
4621 }
4622 final long origId = Binder.clearCallingIdentity();
4623 try {
4624 display.mDisplayContent.registerRemoteAnimations(definition);
4625 } finally {
4626 Binder.restoreCallingIdentity(origId);
4627 }
4628 }
4629 }
4630
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004631 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4632 @Override
4633 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4634 synchronized (mGlobalLock) {
4635 final long origId = Binder.clearCallingIdentity();
4636 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004637 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004638 } finally {
4639 Binder.restoreCallingIdentity(origId);
4640 }
4641 }
4642 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004643
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 @Override
4645 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004646 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004647 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004648 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004649 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004650 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004651 }
4652 }
4653
4654 @Override
4655 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004656 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004657 != PERMISSION_GRANTED) {
4658 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4659 + Binder.getCallingPid()
4660 + ", uid=" + Binder.getCallingUid()
4661 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4662 Slog.w(TAG, msg);
4663 throw new SecurityException(msg);
4664 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004665 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004666 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004667 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004668 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004669 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004670 }
4671 }
4672
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 @Override
4674 public void stopAppSwitches() {
4675 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4676 synchronized (mGlobalLock) {
4677 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004678 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004679 mDidAppSwitch = false;
4680 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4681 }
4682 }
4683
4684 @Override
4685 public void resumeAppSwitches() {
4686 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4687 synchronized (mGlobalLock) {
4688 // Note that we don't execute any pending app switches... we will
4689 // let those wait until either the timeout, or the next start
4690 // activity request.
4691 mAppSwitchesAllowedTime = 0;
4692 }
4693 }
4694
Ricky Wai906af482019-06-03 17:25:28 +01004695 long getLastStopAppSwitchesTime() {
4696 return mLastStopAppSwitchesTime;
4697 }
4698
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004699 void onStartActivitySetDidAppSwitch() {
4700 if (mDidAppSwitch) {
4701 // This is the second allowed switch since we stopped switches, so now just generally
4702 // allow switches. Use case:
4703 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4704 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4705 // anyone to switch again).
4706 mAppSwitchesAllowedTime = 0;
4707 } else {
4708 mDidAppSwitch = true;
4709 }
4710 }
4711
4712 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004713 boolean shouldDisableNonVrUiLocked() {
4714 return mVrController.shouldDisableNonVrUiLocked();
4715 }
4716
Wale Ogunwale53783742018-09-16 10:21:51 -07004717 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 // 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 +00004719 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004721 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4722 + " to main display for VR");
4723 mRootActivityContainer.moveStackToDisplay(
4724 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 }
4726 mH.post(() -> {
4727 if (!mVrController.onVrModeChanged(r)) {
4728 return;
4729 }
4730 synchronized (mGlobalLock) {
4731 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4732 mWindowManager.disableNonVrUi(disableNonVrUi);
4733 if (disableNonVrUi) {
4734 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4735 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004736 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 }
4738 }
4739 });
4740 }
4741
Wale Ogunwale53783742018-09-16 10:21:51 -07004742 @Override
4743 public int getPackageScreenCompatMode(String packageName) {
4744 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4745 synchronized (mGlobalLock) {
4746 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4747 }
4748 }
4749
4750 @Override
4751 public void setPackageScreenCompatMode(String packageName, int mode) {
4752 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4753 "setPackageScreenCompatMode");
4754 synchronized (mGlobalLock) {
4755 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4756 }
4757 }
4758
4759 @Override
4760 public boolean getPackageAskScreenCompat(String packageName) {
4761 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4762 synchronized (mGlobalLock) {
4763 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4764 }
4765 }
4766
4767 @Override
4768 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4769 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4770 "setPackageAskScreenCompat");
4771 synchronized (mGlobalLock) {
4772 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4773 }
4774 }
4775
Wale Ogunwale64258362018-10-16 15:13:37 -07004776 public static String relaunchReasonToString(int relaunchReason) {
4777 switch (relaunchReason) {
4778 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4779 return "window_resize";
4780 case RELAUNCH_REASON_FREE_RESIZE:
4781 return "free_resize";
4782 default:
4783 return null;
4784 }
4785 }
4786
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004787 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004788 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004789 }
4790
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 /** Pokes the task persister. */
4792 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4793 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4794 }
4795
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 boolean isKeyguardLocked() {
4797 return mKeyguardController.isKeyguardLocked();
4798 }
4799
Garfield Tan01548632018-11-27 10:15:48 -08004800 /**
4801 * Clears launch params for the given package.
4802 * @param packageNames the names of the packages of which the launch params are to be cleared
4803 */
4804 @Override
4805 public void clearLaunchParamsForPackages(List<String> packageNames) {
4806 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4807 "clearLaunchParamsForPackages");
4808 synchronized (mGlobalLock) {
4809 for (int i = 0; i < packageNames.size(); ++i) {
4810 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4811 }
4812 }
4813 }
4814
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004815 /**
4816 * Makes the display with the given id a single task instance display. I.e the display can only
4817 * contain one task.
4818 */
4819 @Override
4820 public void setDisplayToSingleTaskInstance(int displayId) {
4821 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4822 "setDisplayToSingleTaskInstance");
4823 final long origId = Binder.clearCallingIdentity();
4824 try {
4825 final ActivityDisplay display =
4826 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4827 if (display != null) {
4828 display.setDisplayToSingleTaskInstance();
4829 }
4830 } finally {
4831 Binder.restoreCallingIdentity(origId);
4832 }
4833 }
4834
Wale Ogunwale31913b52018-10-13 08:29:31 -07004835 void dumpLastANRLocked(PrintWriter pw) {
4836 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4837 if (mLastANRState == null) {
4838 pw.println(" <no ANR has occurred since boot>");
4839 } else {
4840 pw.println(mLastANRState);
4841 }
4842 }
4843
4844 void dumpLastANRTracesLocked(PrintWriter pw) {
4845 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4846
4847 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4848 if (ArrayUtils.isEmpty(files)) {
4849 pw.println(" <no ANR has occurred since boot>");
4850 return;
4851 }
4852 // Find the latest file.
4853 File latest = null;
4854 for (File f : files) {
4855 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4856 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004857 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004858 }
4859 pw.print("File: ");
4860 pw.print(latest.getName());
4861 pw.println();
4862 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4863 String line;
4864 while ((line = in.readLine()) != null) {
4865 pw.println(line);
4866 }
4867 } catch (IOException e) {
4868 pw.print("Unable to read: ");
4869 pw.print(e);
4870 pw.println();
4871 }
4872 }
4873
4874 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4875 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4876 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4877 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4878 }
4879
4880 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4881 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4882 pw.println(header);
4883
Wale Ogunwaled32da472018-11-16 07:19:28 -08004884 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004885 dumpPackage);
4886 boolean needSep = printedAnything;
4887
4888 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004889 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004890 " ResumedActivity: ");
4891 if (printed) {
4892 printedAnything = true;
4893 needSep = false;
4894 }
4895
4896 if (dumpPackage == null) {
4897 if (needSep) {
4898 pw.println();
4899 }
4900 printedAnything = true;
4901 mStackSupervisor.dump(pw, " ");
4902 }
4903
4904 if (!printedAnything) {
4905 pw.println(" (nothing)");
4906 }
4907 }
4908
4909 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004910 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004911 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004912 pw.println(" ");
4913 }
4914
4915 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4916 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4917 getActivityStartController().dump(pw, "", dumpPackage);
4918 }
4919
4920 /**
4921 * There are three things that cmd can be:
4922 * - a flattened component name that matches an existing activity
4923 * - the cmd arg isn't the flattened component name of an existing activity:
4924 * dump all activity whose component contains the cmd as a substring
4925 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004926 * <p>
4927 * The caller should not hold lock when calling this method because it will wait for the
4928 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004929 *
4930 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4931 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4932 */
4933 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4934 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4935 ArrayList<ActivityRecord> activities;
4936
4937 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004938 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004939 dumpFocusedStackOnly);
4940 }
4941
4942 if (activities.size() <= 0) {
4943 return false;
4944 }
4945
4946 String[] newArgs = new String[args.length - opti];
4947 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4948
4949 TaskRecord lastTask = null;
4950 boolean needSep = false;
4951 for (int i = activities.size() - 1; i >= 0; i--) {
4952 ActivityRecord r = activities.get(i);
4953 if (needSep) {
4954 pw.println();
4955 }
4956 needSep = true;
4957 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004958 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004959 if (lastTask != task) {
4960 lastTask = task;
4961 pw.print("TASK "); pw.print(lastTask.affinity);
4962 pw.print(" id="); pw.print(lastTask.taskId);
4963 pw.print(" userId="); pw.println(lastTask.userId);
4964 if (dumpAll) {
4965 lastTask.dump(pw, " ");
4966 }
4967 }
4968 }
4969 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4970 }
4971 return true;
4972 }
4973
4974 /**
4975 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4976 * there is a thread associated with the activity.
4977 */
4978 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4979 final ActivityRecord r, String[] args, boolean dumpAll) {
4980 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004981 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004982 synchronized (mGlobalLock) {
4983 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4984 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4985 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004986 if (r.hasProcess()) {
4987 pw.println(r.app.getPid());
4988 appThread = r.app.getThread();
4989 } else {
4990 pw.println("(not running)");
4991 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004992 if (dumpAll) {
4993 r.dump(pw, innerPrefix);
4994 }
4995 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004996 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 // flush anything that is already in the PrintWriter since the thread is going
4998 // to write to the file descriptor directly
4999 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005000 try (TransferPipe tp = new TransferPipe()) {
5001 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5002 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005003 } catch (IOException e) {
5004 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5005 } catch (RemoteException e) {
5006 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5007 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005008 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005009 }
5010
sanryhuang498e77e2018-12-06 14:57:01 +08005011 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5012 boolean testPssMode) {
5013 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5015 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005016 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005017 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5018 st.toString());
5019 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005020 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5021 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5022 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005023 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5024 testPssMode);
5025 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005026 }
5027
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005028 int getCurrentUserId() {
5029 return mAmInternal.getCurrentUserId();
5030 }
5031
5032 private void enforceNotIsolatedCaller(String caller) {
5033 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5034 throw new SecurityException("Isolated process not allowed to call " + caller);
5035 }
5036 }
5037
Wale Ogunwalef6733932018-06-27 05:14:34 -07005038 public Configuration getConfiguration() {
5039 Configuration ci;
5040 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005041 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005042 ci.userSetLocale = false;
5043 }
5044 return ci;
5045 }
5046
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005047 /**
5048 * Current global configuration information. Contains general settings for the entire system,
5049 * also corresponds to the merged configuration of the default display.
5050 */
5051 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005052 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005053 }
5054
5055 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5056 boolean initLocale) {
5057 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5058 }
5059
5060 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5061 boolean initLocale, boolean deferResume) {
5062 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5063 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5064 UserHandle.USER_NULL, deferResume);
5065 }
5066
Wale Ogunwale59507092018-10-29 09:00:30 -07005067 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068 final long origId = Binder.clearCallingIdentity();
5069 try {
5070 synchronized (mGlobalLock) {
5071 updateConfigurationLocked(values, null, false, true, userId,
5072 false /* deferResume */);
5073 }
5074 } finally {
5075 Binder.restoreCallingIdentity(origId);
5076 }
5077 }
5078
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005079 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5080 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5081 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5082 deferResume, null /* result */);
5083 }
5084
5085 /**
5086 * Do either or both things: (1) change the current configuration, and (2)
5087 * make sure the given activity is running with the (now) current
5088 * configuration. Returns true if the activity has been left running, or
5089 * false if <var>starting</var> is being destroyed to match the new
5090 * configuration.
5091 *
5092 * @param userId is only used when persistent parameter is set to true to persist configuration
5093 * for that particular user
5094 */
5095 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5096 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5097 ActivityTaskManagerService.UpdateConfigurationResult result) {
5098 int changes = 0;
5099 boolean kept = true;
5100
5101 if (mWindowManager != null) {
5102 mWindowManager.deferSurfaceLayout();
5103 }
5104 try {
5105 if (values != null) {
5106 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5107 deferResume);
5108 }
5109
5110 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5111 } finally {
5112 if (mWindowManager != null) {
5113 mWindowManager.continueSurfaceLayout();
5114 }
5115 }
5116
5117 if (result != null) {
5118 result.changes = changes;
5119 result.activityRelaunched = !kept;
5120 }
5121 return kept;
5122 }
5123
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005125 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005126 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005127
5128 final ActivityDisplay defaultDisplay =
5129 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5130
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131 mTempConfig.setTo(getGlobalConfiguration());
5132 final int changes = mTempConfig.updateFrom(values);
5133 if (changes == 0) {
5134 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5135 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5136 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5137 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005138 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 return 0;
5140 }
5141
5142 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5143 "Updating global configuration to: " + values);
5144
5145 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5146 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5147 values.colorMode,
5148 values.densityDpi,
5149 values.fontScale,
5150 values.hardKeyboardHidden,
5151 values.keyboard,
5152 values.keyboardHidden,
5153 values.mcc,
5154 values.mnc,
5155 values.navigation,
5156 values.navigationHidden,
5157 values.orientation,
5158 values.screenHeightDp,
5159 values.screenLayout,
5160 values.screenWidthDp,
5161 values.smallestScreenWidthDp,
5162 values.touchscreen,
5163 values.uiMode);
5164
5165
5166 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5167 final LocaleList locales = values.getLocales();
5168 int bestLocaleIndex = 0;
5169 if (locales.size() > 1) {
5170 if (mSupportedSystemLocales == null) {
5171 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5172 }
5173 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5174 }
5175 SystemProperties.set("persist.sys.locale",
5176 locales.get(bestLocaleIndex).toLanguageTag());
5177 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005178
5179 final Message m = PooledLambda.obtainMessage(
5180 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5181 locales.get(bestLocaleIndex));
5182 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183 }
5184
Yunfan Chen75157d72018-07-27 14:47:21 +09005185 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005186
5187 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005188 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005189
5190 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5191 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005192 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005193
5194 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005195 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196
5197 AttributeCache ac = AttributeCache.instance();
5198 if (ac != null) {
5199 ac.updateConfiguration(mTempConfig);
5200 }
5201
5202 // Make sure all resources in our process are updated right now, so that anyone who is going
5203 // to retrieve resource values after we return will be sure to get the new ones. This is
5204 // especially important during boot, where the first config change needs to guarantee all
5205 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005206 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005207
5208 // We need another copy of global config because we're scheduling some calls instead of
5209 // running them in place. We need to be sure that object we send will be handled unchanged.
5210 final Configuration configCopy = new Configuration(mTempConfig);
5211 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005212 final Message msg = PooledLambda.obtainMessage(
5213 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5214 this, userId, configCopy);
5215 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216 }
5217
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005218 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5219 for (int i = pidMap.size() - 1; i >= 0; i--) {
5220 final int pid = pidMap.keyAt(i);
5221 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005222 if (DEBUG_CONFIGURATION) {
5223 Slog.v(TAG_CONFIGURATION, "Update process config of "
5224 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005226 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227 }
5228
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005229 final Message msg = PooledLambda.obtainMessage(
5230 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5231 mAmInternal, changes, initLocale);
5232 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233
5234 // Override configuration of the default display duplicates global config, so we need to
5235 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005236 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5237 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005238
5239 return changes;
5240 }
5241
Wale Ogunwalef6733932018-06-27 05:14:34 -07005242 private void updateEventDispatchingLocked(boolean booted) {
5243 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5244 }
5245
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005246 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5247 final ContentResolver resolver = mContext.getContentResolver();
5248 Settings.System.putConfigurationForUser(resolver, config, userId);
5249 }
5250
5251 private void sendLocaleToMountDaemonMsg(Locale l) {
5252 try {
5253 IBinder service = ServiceManager.getService("mount");
5254 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5255 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5256 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5257 } catch (RemoteException e) {
5258 Log.e(TAG, "Error storing locale for decryption UI", e);
5259 }
5260 }
5261
Alison Cichowlas3e340502018-08-07 17:15:01 -04005262 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5263 mStartActivitySources.remove(permissionToken);
5264 mExpiredStartAsCallerTokens.add(permissionToken);
5265 }
5266
5267 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5268 mExpiredStartAsCallerTokens.remove(permissionToken);
5269 }
5270
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005271 boolean isActivityStartsLoggingEnabled() {
5272 return mAmInternal.isActivityStartsLoggingEnabled();
5273 }
5274
Michal Karpinski8596ded2018-11-14 14:43:48 +00005275 boolean isBackgroundActivityStartsEnabled() {
5276 return mAmInternal.isBackgroundActivityStartsEnabled();
5277 }
5278
Wale Ogunwalef6733932018-06-27 05:14:34 -07005279 void enableScreenAfterBoot(boolean booted) {
5280 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5281 SystemClock.uptimeMillis());
5282 mWindowManager.enableScreenAfterBoot();
5283
5284 synchronized (mGlobalLock) {
5285 updateEventDispatchingLocked(booted);
5286 }
5287 }
5288
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005289 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5290 if (r == null || !r.hasProcess()) {
5291 return KEY_DISPATCHING_TIMEOUT_MS;
5292 }
5293 return getInputDispatchingTimeoutLocked(r.app);
5294 }
5295
5296 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005297 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005298 }
5299
Wale Ogunwalef6733932018-06-27 05:14:34 -07005300 /**
5301 * Decide based on the configuration whether we should show the ANR,
5302 * crash, etc dialogs. The idea is that if there is no affordance to
5303 * press the on-screen buttons, or the user experience would be more
5304 * greatly impacted than the crash itself, we shouldn't show the dialog.
5305 *
5306 * A thought: SystemUI might also want to get told about this, the Power
5307 * dialog / global actions also might want different behaviors.
5308 */
5309 private void updateShouldShowDialogsLocked(Configuration config) {
5310 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5311 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5312 && config.navigation == Configuration.NAVIGATION_NONAV);
5313 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5314 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5315 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5316 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5317 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5318 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5319 HIDE_ERROR_DIALOGS, 0) != 0;
5320 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5321 }
5322
5323 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5324 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5325 FONT_SCALE, 1.0f, userId);
5326
5327 synchronized (this) {
5328 if (getGlobalConfiguration().fontScale == scaleFactor) {
5329 return;
5330 }
5331
5332 final Configuration configuration
5333 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5334 configuration.fontScale = scaleFactor;
5335 updatePersistentConfiguration(configuration, userId);
5336 }
5337 }
5338
5339 // Actually is sleeping or shutting down or whatever else in the future
5340 // is an inactive state.
5341 boolean isSleepingOrShuttingDownLocked() {
5342 return isSleepingLocked() || mShuttingDown;
5343 }
5344
5345 boolean isSleepingLocked() {
5346 return mSleeping;
5347 }
5348
Riddle Hsu16567132018-08-16 21:37:47 +08005349 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005350 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005351 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005352 if (task.isActivityTypeStandard()) {
5353 if (mCurAppTimeTracker != r.appTimeTracker) {
5354 // We are switching app tracking. Complete the current one.
5355 if (mCurAppTimeTracker != null) {
5356 mCurAppTimeTracker.stop();
5357 mH.obtainMessage(
5358 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005359 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 mCurAppTimeTracker = null;
5361 }
5362 if (r.appTimeTracker != null) {
5363 mCurAppTimeTracker = r.appTimeTracker;
5364 startTimeTrackingFocusedActivityLocked();
5365 }
5366 } else {
5367 startTimeTrackingFocusedActivityLocked();
5368 }
5369 } else {
5370 r.appTimeTracker = null;
5371 }
5372 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5373 // TODO: Probably not, because we don't want to resume voice on switching
5374 // back to this activity
5375 if (task.voiceInteractor != null) {
5376 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5377 } else {
5378 finishRunningVoiceLocked();
5379
5380 if (mLastResumedActivity != null) {
5381 final IVoiceInteractionSession session;
5382
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005383 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005384 if (lastResumedActivityTask != null
5385 && lastResumedActivityTask.voiceSession != null) {
5386 session = lastResumedActivityTask.voiceSession;
5387 } else {
5388 session = mLastResumedActivity.voiceSession;
5389 }
5390
5391 if (session != null) {
5392 // We had been in a voice interaction session, but now focused has
5393 // move to something different. Just finish the session, we can't
5394 // return to it and retain the proper state and synchronization with
5395 // the voice interaction service.
5396 finishVoiceTask(session);
5397 }
5398 }
5399 }
5400
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005401 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5402 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005403 }
5404 updateResumedAppTrace(r);
5405 mLastResumedActivity = r;
5406
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005407 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005408
5409 applyUpdateLockStateLocked(r);
5410 applyUpdateVrModeLocked(r);
5411
5412 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005413 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005414 r == null ? "NULL" : r.shortComponentName,
5415 reason);
5416 }
5417
5418 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5419 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005420 final ActivityTaskManagerInternal.SleepToken token =
5421 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 updateSleepIfNeededLocked();
5423 return token;
5424 }
5425 }
5426
5427 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005428 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005429 final boolean wasSleeping = mSleeping;
5430 boolean updateOomAdj = false;
5431
5432 if (!shouldSleep) {
5433 // If wasSleeping is true, we need to wake up activity manager state from when
5434 // we started sleeping. In either case, we need to apply the sleep tokens, which
5435 // will wake up stacks or put them to sleep as appropriate.
5436 if (wasSleeping) {
5437 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005438 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5439 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 startTimeTrackingFocusedActivityLocked();
5441 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005442 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5444 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005445 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 if (wasSleeping) {
5447 updateOomAdj = true;
5448 }
5449 } else if (!mSleeping && shouldSleep) {
5450 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005451 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5452 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005453 if (mCurAppTimeTracker != null) {
5454 mCurAppTimeTracker.stop();
5455 }
5456 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005457 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 mStackSupervisor.goingToSleepLocked();
5459 updateResumedAppTrace(null /* resumed */);
5460 updateOomAdj = true;
5461 }
5462 if (updateOomAdj) {
5463 mH.post(mAmInternal::updateOomAdj);
5464 }
5465 }
5466
5467 void updateOomAdj() {
5468 mH.post(mAmInternal::updateOomAdj);
5469 }
5470
Wale Ogunwale53783742018-09-16 10:21:51 -07005471 void updateCpuStats() {
5472 mH.post(mAmInternal::updateCpuStats);
5473 }
5474
Hui Yu03d12402018-12-06 18:00:37 -08005475 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5476 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005477 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5478 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005479 mH.sendMessage(m);
5480 }
5481
Hui Yu03d12402018-12-06 18:00:37 -08005482 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005483 ComponentName taskRoot = null;
5484 final TaskRecord task = activity.getTaskRecord();
5485 if (task != null) {
5486 final ActivityRecord rootActivity = task.getRootActivity();
5487 if (rootActivity != null) {
5488 taskRoot = rootActivity.mActivityComponent;
5489 }
5490 }
5491
Hui Yu03d12402018-12-06 18:00:37 -08005492 final Message m = PooledLambda.obtainMessage(
5493 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005494 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005495 mH.sendMessage(m);
5496 }
5497
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005498 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5499 String hostingType) {
5500 try {
5501 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5502 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5503 + activity.processName);
5504 }
5505 // Post message to start process to avoid possible deadlock of calling into AMS with the
5506 // ATMS lock held.
5507 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5508 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5509 isTop, hostingType, activity.intent.getComponent());
5510 mH.sendMessage(m);
5511 } finally {
5512 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5513 }
5514 }
5515
Wale Ogunwale53783742018-09-16 10:21:51 -07005516 void setBooting(boolean booting) {
5517 mAmInternal.setBooting(booting);
5518 }
5519
5520 boolean isBooting() {
5521 return mAmInternal.isBooting();
5522 }
5523
5524 void setBooted(boolean booted) {
5525 mAmInternal.setBooted(booted);
5526 }
5527
5528 boolean isBooted() {
5529 return mAmInternal.isBooted();
5530 }
5531
5532 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5533 mH.post(() -> {
5534 if (finishBooting) {
5535 mAmInternal.finishBooting();
5536 }
5537 if (enableScreen) {
5538 mInternal.enableScreenAfterBoot(isBooted());
5539 }
5540 });
5541 }
5542
5543 void setHeavyWeightProcess(ActivityRecord root) {
5544 mHeavyWeightProcess = root.app;
5545 final Message m = PooledLambda.obtainMessage(
5546 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005547 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005548 mH.sendMessage(m);
5549 }
5550
5551 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5552 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5553 return;
5554 }
5555
5556 mHeavyWeightProcess = null;
5557 final Message m = PooledLambda.obtainMessage(
5558 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5559 proc.mUserId);
5560 mH.sendMessage(m);
5561 }
5562
5563 private void cancelHeavyWeightProcessNotification(int userId) {
5564 final INotificationManager inm = NotificationManager.getService();
5565 if (inm == null) {
5566 return;
5567 }
5568 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005569 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005570 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5571 } catch (RuntimeException e) {
5572 Slog.w(TAG, "Error canceling notification for service", e);
5573 } catch (RemoteException e) {
5574 }
5575
5576 }
5577
5578 private void postHeavyWeightProcessNotification(
5579 WindowProcessController proc, Intent intent, int userId) {
5580 if (proc == null) {
5581 return;
5582 }
5583
5584 final INotificationManager inm = NotificationManager.getService();
5585 if (inm == null) {
5586 return;
5587 }
5588
5589 try {
5590 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5591 String text = mContext.getString(R.string.heavy_weight_notification,
5592 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5593 Notification notification =
5594 new Notification.Builder(context,
5595 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5596 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5597 .setWhen(0)
5598 .setOngoing(true)
5599 .setTicker(text)
5600 .setColor(mContext.getColor(
5601 com.android.internal.R.color.system_notification_accent_color))
5602 .setContentTitle(text)
5603 .setContentText(
5604 mContext.getText(R.string.heavy_weight_notification_detail))
5605 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5606 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5607 new UserHandle(userId)))
5608 .build();
5609 try {
5610 inm.enqueueNotificationWithTag("android", "android", null,
5611 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5612 } catch (RuntimeException e) {
5613 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5614 } catch (RemoteException e) {
5615 }
5616 } catch (PackageManager.NameNotFoundException e) {
5617 Slog.w(TAG, "Unable to create context for heavy notification", e);
5618 }
5619
5620 }
5621
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005622 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5623 IBinder token, String resultWho, int requestCode, Intent[] intents,
5624 String[] resolvedTypes, int flags, Bundle bOptions) {
5625
5626 ActivityRecord activity = null;
5627 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5628 activity = ActivityRecord.isInStackLocked(token);
5629 if (activity == null) {
5630 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5631 return null;
5632 }
5633 if (activity.finishing) {
5634 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5635 return null;
5636 }
5637 }
5638
5639 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5640 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5641 bOptions);
5642 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5643 if (noCreate) {
5644 return rec;
5645 }
5646 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5647 if (activity.pendingResults == null) {
5648 activity.pendingResults = new HashSet<>();
5649 }
5650 activity.pendingResults.add(rec.ref);
5651 }
5652 return rec;
5653 }
5654
Andrii Kulian52d255c2018-07-13 11:32:19 -07005655 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005656 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005657 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005658 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5659 mCurAppTimeTracker.start(resumedActivity.packageName);
5660 }
5661 }
5662
5663 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5664 if (mTracedResumedActivity != null) {
5665 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5666 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5667 }
5668 if (resumed != null) {
5669 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5670 constructResumedTraceName(resumed.packageName), 0);
5671 }
5672 mTracedResumedActivity = resumed;
5673 }
5674
5675 private String constructResumedTraceName(String packageName) {
5676 return "focused app: " + packageName;
5677 }
5678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005679 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005680 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005681 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005682 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005683 // mainStack is null during startup.
5684 if (mainStack != null) {
5685 if (changes != 0 && starting == null) {
5686 // If the configuration changed, and the caller is not already
5687 // in the process of starting an activity, then find the top
5688 // activity to check if its configuration needs to change.
5689 starting = mainStack.topRunningActivityLocked();
5690 }
5691
5692 if (starting != null) {
5693 kept = starting.ensureActivityConfiguration(changes,
5694 false /* preserveWindow */);
5695 // And we need to make sure at this point that all other activities
5696 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005697 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005698 !PRESERVE_WINDOWS);
5699 }
5700 }
5701
5702 return kept;
5703 }
5704
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005705 void scheduleAppGcsLocked() {
5706 mH.post(() -> mAmInternal.scheduleAppGcs());
5707 }
5708
Wale Ogunwale53783742018-09-16 10:21:51 -07005709 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5710 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5711 }
5712
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005713 /**
5714 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5715 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5716 * on demand.
5717 */
5718 IPackageManager getPackageManager() {
5719 return AppGlobals.getPackageManager();
5720 }
5721
5722 PackageManagerInternal getPackageManagerInternalLocked() {
5723 if (mPmInternal == null) {
5724 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5725 }
5726 return mPmInternal;
5727 }
5728
Hai Zhangf4da9be2019-05-01 13:46:06 +08005729 PermissionPolicyInternal getPermissionPolicyInternal() {
5730 if (mPermissionPolicyInternal == null) {
5731 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5732 }
5733 return mPermissionPolicyInternal;
5734 }
5735
Wale Ogunwale008163e2018-07-23 23:11:08 -07005736 AppWarnings getAppWarningsLocked() {
5737 return mAppWarnings;
5738 }
5739
Wale Ogunwale214f3482018-10-04 11:00:47 -07005740 Intent getHomeIntent() {
5741 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5742 intent.setComponent(mTopComponent);
5743 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5744 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5745 intent.addCategory(Intent.CATEGORY_HOME);
5746 }
5747 return intent;
5748 }
5749
Chilun2ef71f72018-11-16 17:57:15 +08005750 /**
5751 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5752 * activities.
5753 *
5754 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5755 * component defined in config_secondaryHomeComponent.
5756 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5757 */
5758 Intent getSecondaryHomeIntent(String preferredPackage) {
5759 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005760 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5761 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5762 if (preferredPackage == null || useSystemProvidedLauncher) {
5763 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005764 final String secondaryHomeComponent = mContext.getResources().getString(
5765 com.android.internal.R.string.config_secondaryHomeComponent);
5766 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5767 } else {
5768 intent.setPackage(preferredPackage);
5769 }
5770 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5771 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5772 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5773 }
5774 return intent;
5775 }
5776
Wale Ogunwale214f3482018-10-04 11:00:47 -07005777 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5778 if (info == null) return null;
5779 ApplicationInfo newInfo = new ApplicationInfo(info);
5780 newInfo.initForUser(userId);
5781 return newInfo;
5782 }
5783
Wale Ogunwale9c103022018-10-18 07:44:54 -07005784 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005785 if (uid == SYSTEM_UID) {
5786 // The system gets to run in any process. If there are multiple processes with the same
5787 // uid, just pick the first (this should never happen).
5788 final SparseArray<WindowProcessController> procs =
5789 mProcessNames.getMap().get(processName);
5790 if (procs == null) return null;
5791 final int procCount = procs.size();
5792 for (int i = 0; i < procCount; i++) {
5793 final int procUid = procs.keyAt(i);
5794 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5795 // Don't use an app process or different user process for system component.
5796 continue;
5797 }
5798 return procs.valueAt(i);
5799 }
5800 }
5801
5802 return mProcessNames.get(processName, uid);
5803 }
5804
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005805 WindowProcessController getProcessController(IApplicationThread thread) {
5806 if (thread == null) {
5807 return null;
5808 }
5809
5810 final IBinder threadBinder = thread.asBinder();
5811 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5812 for (int i = pmap.size()-1; i >= 0; i--) {
5813 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5814 for (int j = procs.size() - 1; j >= 0; j--) {
5815 final WindowProcessController proc = procs.valueAt(j);
5816 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5817 return proc;
5818 }
5819 }
5820 }
5821
5822 return null;
5823 }
5824
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005825 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005826 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005827 if (proc == null) return null;
5828 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5829 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005830 }
5831 return null;
5832 }
5833
Riddle Hsua0536432019-02-16 00:38:59 +08005834 int getUidState(int uid) {
5835 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005836 }
5837
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005838 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005839 // A uid is considered to be foreground if it has a visible non-toast window.
5840 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005841 }
5842
Ricky Wai96f5c352019-04-10 18:40:17 +01005843 boolean isDeviceOwner(int uid) {
5844 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005845 }
5846
Ricky Wai96f5c352019-04-10 18:40:17 +01005847 void setDeviceOwnerUid(int uid) {
5848 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005849 }
5850
Wale Ogunwale9de19442018-10-18 19:05:03 -07005851 /**
5852 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5853 * the whitelist
5854 */
5855 String getPendingTempWhitelistTagForUidLocked(int uid) {
5856 return mPendingTempWhitelist.get(uid);
5857 }
5858
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005859 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5860 if (true || Build.IS_USER) {
5861 return;
5862 }
5863
5864 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5865 StrictMode.allowThreadDiskWrites();
5866 try {
5867 File tracesDir = new File("/data/anr");
5868 File tracesFile = null;
5869 try {
5870 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5871
5872 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005873 String timeString =
5874 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5875 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005876 sb.append(": ");
5877 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5878 sb.append(" since ");
5879 sb.append(msg);
5880 FileOutputStream fos = new FileOutputStream(tracesFile);
5881 fos.write(sb.toString().getBytes());
5882 if (app == null) {
5883 fos.write("\n*** No application process!".getBytes());
5884 }
5885 fos.close();
5886 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5887 } catch (IOException e) {
5888 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5889 return;
5890 }
5891
5892 if (app != null && app.getPid() > 0) {
5893 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5894 firstPids.add(app.getPid());
5895 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5896 }
5897
5898 File lastTracesFile = null;
5899 File curTracesFile = null;
5900 for (int i=9; i>=0; i--) {
5901 String name = String.format(Locale.US, "slow%02d.txt", i);
5902 curTracesFile = new File(tracesDir, name);
5903 if (curTracesFile.exists()) {
5904 if (lastTracesFile != null) {
5905 curTracesFile.renameTo(lastTracesFile);
5906 } else {
5907 curTracesFile.delete();
5908 }
5909 }
5910 lastTracesFile = curTracesFile;
5911 }
5912 tracesFile.renameTo(curTracesFile);
5913 } finally {
5914 StrictMode.setThreadPolicy(oldPolicy);
5915 }
5916 }
5917
Michal Karpinskida34cd42019-04-02 19:46:52 +01005918 boolean isAssociatedCompanionApp(int userId, int uid) {
5919 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5920 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005921 return false;
5922 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005923 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005924 }
5925
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005926 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005927 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005928
5929
Wale Ogunwale98875612018-10-12 07:53:02 -07005930 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5931 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005932
Riddle Hsud93a6c42018-11-29 21:50:06 +08005933 H(Looper looper) {
5934 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005935 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005936
5937 @Override
5938 public void handleMessage(Message msg) {
5939 switch (msg.what) {
5940 case REPORT_TIME_TRACKER_MSG: {
5941 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5942 tracker.deliverResult(mContext);
5943 } break;
5944 }
5945 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005946 }
5947
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005948 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005949 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005950
5951 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005952 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005953 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005954
5955 @Override
5956 public void handleMessage(Message msg) {
5957 switch (msg.what) {
5958 case DISMISS_DIALOG_UI_MSG: {
5959 final Dialog d = (Dialog) msg.obj;
5960 d.dismiss();
5961 break;
5962 }
5963 }
5964 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005965 }
5966
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005967 final class LocalService extends ActivityTaskManagerInternal {
5968 @Override
5969 public SleepToken acquireSleepToken(String tag, int displayId) {
5970 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005971 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005972 }
5973
5974 @Override
5975 public ComponentName getHomeActivityForUser(int userId) {
5976 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005977 final ActivityRecord homeActivity =
5978 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005979 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005980 }
5981 }
5982
5983 @Override
5984 public void onLocalVoiceInteractionStarted(IBinder activity,
5985 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5986 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005987 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005988 }
5989 }
5990
5991 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005992 public void notifyAppTransitionStarting(SparseIntArray reasons,
5993 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005994 synchronized (mGlobalLock) {
5995 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5996 reasons, timestamp);
5997 }
5998 }
5999
6000 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006001 public void notifySingleTaskDisplayDrawn(int displayId) {
6002 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6003 }
6004
6005 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006006 public void notifyAppTransitionFinished() {
6007 synchronized (mGlobalLock) {
6008 mStackSupervisor.notifyAppTransitionDone();
6009 }
6010 }
6011
6012 @Override
6013 public void notifyAppTransitionCancelled() {
6014 synchronized (mGlobalLock) {
6015 mStackSupervisor.notifyAppTransitionDone();
6016 }
6017 }
6018
6019 @Override
6020 public List<IBinder> getTopVisibleActivities() {
6021 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006022 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006023 }
6024 }
6025
6026 @Override
6027 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6028 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006029 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006030 }
6031 }
6032
6033 @Override
6034 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6035 Bundle bOptions) {
6036 Preconditions.checkNotNull(intents, "intents");
6037 final String[] resolvedTypes = new String[intents.length];
6038
6039 // UID of the package on user userId.
6040 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6041 // packageUid may not be initialized.
6042 int packageUid = 0;
6043 final long ident = Binder.clearCallingIdentity();
6044
6045 try {
6046 for (int i = 0; i < intents.length; i++) {
6047 resolvedTypes[i] =
6048 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6049 }
6050
6051 packageUid = AppGlobals.getPackageManager().getPackageUid(
6052 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6053 } catch (RemoteException e) {
6054 // Shouldn't happen.
6055 } finally {
6056 Binder.restoreCallingIdentity(ident);
6057 }
6058
Riddle Hsu591bf612019-02-14 17:55:31 +08006059 return getActivityStartController().startActivitiesInPackage(
6060 packageUid, packageName,
6061 intents, resolvedTypes, null /* resultTo */,
6062 SafeActivityOptions.fromBundle(bOptions), userId,
6063 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6064 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006065 }
6066
6067 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006068 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6069 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6070 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6071 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006072 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006073 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006074 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6075 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6076 userId, validateIncomingUser, originatingPendingIntent,
6077 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006078 }
6079 }
6080
6081 @Override
6082 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6083 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6084 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6085 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006086 PendingIntentRecord originatingPendingIntent,
6087 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006088 synchronized (mGlobalLock) {
6089 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6090 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6091 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006092 validateIncomingUser, originatingPendingIntent,
6093 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006094 }
6095 }
6096
6097 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006098 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6099 Intent intent, Bundle options, int userId) {
6100 return ActivityTaskManagerService.this.startActivityAsUser(
6101 caller, callerPacakge, intent,
6102 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6103 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6104 false /*validateIncomingUser*/);
6105 }
6106
6107 @Override
lumark588a3e82018-07-20 18:53:54 +08006108 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006109 synchronized (mGlobalLock) {
6110
6111 // We might change the visibilities here, so prepare an empty app transition which
6112 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006113 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006114 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006115 if (activityDisplay == null) {
6116 return;
6117 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006118 final DisplayContent dc = activityDisplay.mDisplayContent;
6119 final boolean wasTransitionSet =
6120 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006121 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006122 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006124 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125
6126 // If there was a transition set already we don't want to interfere with it as we
6127 // might be starting it too early.
6128 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006129 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006130 }
6131 }
6132 if (callback != null) {
6133 callback.run();
6134 }
6135 }
6136
6137 @Override
6138 public void notifyKeyguardTrustedChanged() {
6139 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006140 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006141 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006142 }
6143 }
6144 }
6145
6146 /**
6147 * Called after virtual display Id is updated by
6148 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6149 * {@param vrVr2dDisplayId}.
6150 */
6151 @Override
6152 public void setVr2dDisplayId(int vr2dDisplayId) {
6153 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6154 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006155 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006156 }
6157 }
6158
6159 @Override
6160 public void setFocusedActivity(IBinder token) {
6161 synchronized (mGlobalLock) {
6162 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6163 if (r == null) {
6164 throw new IllegalArgumentException(
6165 "setFocusedActivity: No activity record matching token=" + token);
6166 }
Louis Chang19443452018-10-09 12:10:21 +08006167 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006168 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006169 }
6170 }
6171 }
6172
6173 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006175 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176 }
6177
6178 @Override
6179 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006180 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006181 }
6182
6183 @Override
6184 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006185 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006186 }
6187
6188 @Override
6189 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6190 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6191 }
6192
6193 @Override
6194 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006195 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006196 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006197
6198 @Override
6199 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6200 synchronized (mGlobalLock) {
6201 mActiveVoiceInteractionServiceComponent = component;
6202 }
6203 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006204
6205 @Override
6206 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6207 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6208 return;
6209 }
6210 synchronized (mGlobalLock) {
6211 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6212 if (types == null) {
6213 if (uid < 0) {
6214 return;
6215 }
6216 types = new ArrayMap<>();
6217 mAllowAppSwitchUids.put(userId, types);
6218 }
6219 if (uid < 0) {
6220 types.remove(type);
6221 } else {
6222 types.put(type, uid);
6223 }
6224 }
6225 }
6226
6227 @Override
6228 public void onUserStopped(int userId) {
6229 synchronized (mGlobalLock) {
6230 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6231 mAllowAppSwitchUids.remove(userId);
6232 }
6233 }
6234
6235 @Override
6236 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6237 synchronized (mGlobalLock) {
6238 return ActivityTaskManagerService.this.isGetTasksAllowed(
6239 caller, callingPid, callingUid);
6240 }
6241 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006242
Riddle Hsua0536432019-02-16 00:38:59 +08006243 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006244 @Override
6245 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006246 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006247 mProcessNames.put(proc.mName, proc.mUid, proc);
6248 }
6249 }
6250
Riddle Hsua0536432019-02-16 00:38:59 +08006251 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006252 @Override
6253 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006254 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006255 mProcessNames.remove(name, uid);
6256 }
6257 }
6258
Riddle Hsua0536432019-02-16 00:38:59 +08006259 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006260 @Override
6261 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006262 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006263 if (proc == mHomeProcess) {
6264 mHomeProcess = null;
6265 }
6266 if (proc == mPreviousProcess) {
6267 mPreviousProcess = null;
6268 }
6269 }
6270 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006271
Riddle Hsua0536432019-02-16 00:38:59 +08006272 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006273 @Override
6274 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006275 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006276 return mTopProcessState;
6277 }
6278 }
6279
Riddle Hsua0536432019-02-16 00:38:59 +08006280 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006281 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006282 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006283 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006284 return proc == mHeavyWeightProcess;
6285 }
6286 }
6287
Riddle Hsua0536432019-02-16 00:38:59 +08006288 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006289 @Override
6290 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006291 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006292 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6293 }
6294 }
6295
6296 @Override
6297 public void finishHeavyWeightApp() {
6298 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006299 if (mHeavyWeightProcess != null) {
6300 mHeavyWeightProcess.finishActivities();
6301 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006302 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6303 mHeavyWeightProcess);
6304 }
6305 }
6306
Riddle Hsua0536432019-02-16 00:38:59 +08006307 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006308 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006309 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006310 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006311 return isSleepingLocked();
6312 }
6313 }
6314
6315 @Override
6316 public boolean isShuttingDown() {
6317 synchronized (mGlobalLock) {
6318 return mShuttingDown;
6319 }
6320 }
6321
6322 @Override
6323 public boolean shuttingDown(boolean booted, int timeout) {
6324 synchronized (mGlobalLock) {
6325 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006326 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006327 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006328 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006329 return mStackSupervisor.shutdownLocked(timeout);
6330 }
6331 }
6332
6333 @Override
6334 public void enableScreenAfterBoot(boolean booted) {
6335 synchronized (mGlobalLock) {
6336 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6337 SystemClock.uptimeMillis());
6338 mWindowManager.enableScreenAfterBoot();
6339 updateEventDispatchingLocked(booted);
6340 }
6341 }
6342
6343 @Override
6344 public boolean showStrictModeViolationDialog() {
6345 synchronized (mGlobalLock) {
6346 return mShowDialogs && !mSleeping && !mShuttingDown;
6347 }
6348 }
6349
6350 @Override
6351 public void showSystemReadyErrorDialogsIfNeeded() {
6352 synchronized (mGlobalLock) {
6353 try {
6354 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6355 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6356 + " data partition or your device will be unstable.");
6357 mUiHandler.post(() -> {
6358 if (mShowDialogs) {
6359 AlertDialog d = new BaseErrorDialog(mUiContext);
6360 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6361 d.setCancelable(false);
6362 d.setTitle(mUiContext.getText(R.string.android_system_label));
6363 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6364 d.setButton(DialogInterface.BUTTON_POSITIVE,
6365 mUiContext.getText(R.string.ok),
6366 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6367 d.show();
6368 }
6369 });
6370 }
6371 } catch (RemoteException e) {
6372 }
6373
6374 if (!Build.isBuildConsistent()) {
6375 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6376 mUiHandler.post(() -> {
6377 if (mShowDialogs) {
6378 AlertDialog d = new BaseErrorDialog(mUiContext);
6379 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6380 d.setCancelable(false);
6381 d.setTitle(mUiContext.getText(R.string.android_system_label));
6382 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6383 d.setButton(DialogInterface.BUTTON_POSITIVE,
6384 mUiContext.getText(R.string.ok),
6385 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6386 d.show();
6387 }
6388 });
6389 }
6390 }
6391 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006392
6393 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006394 public void onProcessMapped(int pid, WindowProcessController proc) {
6395 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006396 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006397 }
6398 }
6399
6400 @Override
6401 public void onProcessUnMapped(int pid) {
6402 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006403 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006404 }
6405 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006406
6407 @Override
6408 public void onPackageDataCleared(String name) {
6409 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006410 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006411 mAppWarnings.onPackageDataCleared(name);
6412 }
6413 }
6414
6415 @Override
6416 public void onPackageUninstalled(String name) {
6417 synchronized (mGlobalLock) {
6418 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006419 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006420 }
6421 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006422
6423 @Override
6424 public void onPackageAdded(String name, boolean replacing) {
6425 synchronized (mGlobalLock) {
6426 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6427 }
6428 }
6429
6430 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006431 public void onPackageReplaced(ApplicationInfo aInfo) {
6432 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006433 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006434 }
6435 }
6436
6437 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006438 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6439 synchronized (mGlobalLock) {
6440 return compatibilityInfoForPackageLocked(ai);
6441 }
6442 }
6443
Yunfan Chen75157d72018-07-27 14:47:21 +09006444 /**
6445 * Set the corresponding display information for the process global configuration. To be
6446 * called when we need to show IME on a different display.
6447 *
6448 * @param pid The process id associated with the IME window.
6449 * @param displayId The ID of the display showing the IME.
6450 */
6451 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006452 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006453 // Don't update process-level configuration for Multi-Client IME process since other
6454 // IMEs on other displays will also receive this configuration change due to IME
6455 // services use the same application config/context.
6456 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006457
Yunfan Chen75157d72018-07-27 14:47:21 +09006458 if (pid == MY_PID || pid < 0) {
6459 if (DEBUG_CONFIGURATION) {
6460 Slog.w(TAG,
6461 "Trying to update display configuration for system/invalid process.");
6462 }
6463 return;
6464 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006465 synchronized (mGlobalLock) {
6466 final ActivityDisplay activityDisplay =
6467 mRootActivityContainer.getActivityDisplay(displayId);
6468 if (activityDisplay == null) {
6469 // Call might come when display is not yet added or has been removed.
6470 if (DEBUG_CONFIGURATION) {
6471 Slog.w(TAG, "Trying to update display configuration for non-existing "
6472 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006473 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006474 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006475 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006476 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006477 if (process == null) {
6478 if (DEBUG_CONFIGURATION) {
6479 Slog.w(TAG, "Trying to update display configuration for invalid "
6480 + "process, pid=" + pid);
6481 }
6482 return;
6483 }
lumarkddc77fb2019-06-27 22:22:23 +08006484 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006485 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6486 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006487 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006488
6489 @Override
6490 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006491 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006492 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006493 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6494 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006495 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006496 }
6497 }
6498 }
6499
6500 @Override
6501 public void clearPendingResultForActivity(IBinder activityToken,
6502 WeakReference<PendingIntentRecord> pir) {
6503 synchronized (mGlobalLock) {
6504 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6505 if (r != null && r.pendingResults != null) {
6506 r.pendingResults.remove(pir);
6507 }
6508 }
6509 }
6510
6511 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006512 public ActivityTokens getTopActivityForTask(int taskId) {
6513 synchronized (mGlobalLock) {
6514 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6515 if (taskRecord == null) {
6516 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6517 + " Requested task not found");
6518 return null;
6519 }
6520 final ActivityRecord activity = taskRecord.getTopActivity();
6521 if (activity == null) {
6522 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6523 + " Requested activity not found");
6524 return null;
6525 }
6526 if (!activity.attachedToProcess()) {
6527 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6528 + activity);
6529 return null;
6530 }
6531 return new ActivityTokens(activity.appToken, activity.assistToken,
6532 activity.app.getThread());
6533 }
6534 }
6535
6536 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006537 public IIntentSender getIntentSender(int type, String packageName,
6538 int callingUid, int userId, IBinder token, String resultWho,
6539 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6540 Bundle bOptions) {
6541 synchronized (mGlobalLock) {
6542 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6543 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6544 }
6545 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006546
6547 @Override
6548 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6549 synchronized (mGlobalLock) {
6550 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6551 if (r == null) {
6552 return null;
6553 }
6554 if (r.mServiceConnectionsHolder == null) {
6555 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6556 ActivityTaskManagerService.this, r);
6557 }
6558
6559 return r.mServiceConnectionsHolder;
6560 }
6561 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006562
6563 @Override
6564 public Intent getHomeIntent() {
6565 synchronized (mGlobalLock) {
6566 return ActivityTaskManagerService.this.getHomeIntent();
6567 }
6568 }
6569
6570 @Override
6571 public boolean startHomeActivity(int userId, String reason) {
6572 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006573 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006574 }
6575 }
6576
6577 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006578 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006579 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006580 synchronized (mGlobalLock) {
6581 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006582 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006583 }
Chilun8b1f1be2019-03-13 17:14:36 +08006584 }
6585
6586 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006587 public boolean startHomeOnAllDisplays(int userId, String reason) {
6588 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006589 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006590 }
6591 }
6592
Riddle Hsua0536432019-02-16 00:38:59 +08006593 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006594 @Override
6595 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006596 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006597 if (mFactoryTest == FACTORY_TEST_OFF) {
6598 return false;
6599 }
6600 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6601 && wpc.mName.equals(mTopComponent.getPackageName())) {
6602 return true;
6603 }
6604 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6605 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6606 }
6607 }
6608
6609 @Override
6610 public void updateTopComponentForFactoryTest() {
6611 synchronized (mGlobalLock) {
6612 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6613 return;
6614 }
6615 final ResolveInfo ri = mContext.getPackageManager()
6616 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6617 final CharSequence errorMsg;
6618 if (ri != null) {
6619 final ActivityInfo ai = ri.activityInfo;
6620 final ApplicationInfo app = ai.applicationInfo;
6621 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6622 mTopAction = Intent.ACTION_FACTORY_TEST;
6623 mTopData = null;
6624 mTopComponent = new ComponentName(app.packageName, ai.name);
6625 errorMsg = null;
6626 } else {
6627 errorMsg = mContext.getResources().getText(
6628 com.android.internal.R.string.factorytest_not_system);
6629 }
6630 } else {
6631 errorMsg = mContext.getResources().getText(
6632 com.android.internal.R.string.factorytest_no_action);
6633 }
6634 if (errorMsg == null) {
6635 return;
6636 }
6637
6638 mTopAction = null;
6639 mTopData = null;
6640 mTopComponent = null;
6641 mUiHandler.post(() -> {
6642 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6643 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006644 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006645 });
6646 }
6647 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006648
Riddle Hsua0536432019-02-16 00:38:59 +08006649 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006650 @Override
6651 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6652 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006653 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006655 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006656
6657 wpc.clearRecentTasks();
6658 wpc.clearActivities();
6659
6660 if (wpc.isInstrumenting()) {
6661 finishInstrumentationCallback.run();
6662 }
6663
Jorim Jaggid0752812018-10-16 16:07:20 +02006664 if (!restarting && hasVisibleActivities) {
6665 mWindowManager.deferSurfaceLayout();
6666 try {
6667 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6668 // If there was nothing to resume, and we are not already restarting
6669 // this process, but there is a visible activity that is hosted by the
6670 // process...then make sure all visible activities are running, taking
6671 // care of restarting this process.
6672 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6673 !PRESERVE_WINDOWS);
6674 }
6675 } finally {
6676 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006677 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006678 }
6679 }
6680 }
6681
6682 @Override
6683 public void closeSystemDialogs(String reason) {
6684 enforceNotIsolatedCaller("closeSystemDialogs");
6685
6686 final int pid = Binder.getCallingPid();
6687 final int uid = Binder.getCallingUid();
6688 final long origId = Binder.clearCallingIdentity();
6689 try {
6690 synchronized (mGlobalLock) {
6691 // Only allow this from foreground processes, so that background
6692 // applications can't abuse it to prevent system UI from being shown.
6693 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006694 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006695 if (!proc.isPerceptible()) {
6696 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6697 + " from background process " + proc);
6698 return;
6699 }
6700 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 mWindowManager.closeSystemDialogs(reason);
6702
Wale Ogunwaled32da472018-11-16 07:19:28 -08006703 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006704 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006705 // Call into AM outside the synchronized block.
6706 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 } finally {
6708 Binder.restoreCallingIdentity(origId);
6709 }
6710 }
6711
6712 @Override
6713 public void cleanupDisabledPackageComponents(
6714 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6715 synchronized (mGlobalLock) {
6716 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006717 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006719 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006720 mStackSupervisor.scheduleIdleLocked();
6721 }
6722
6723 // Clean-up disabled tasks
6724 getRecentTasks().cleanupDisabledPackageTasksLocked(
6725 packageName, disabledClasses, userId);
6726 }
6727 }
6728
6729 @Override
6730 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6731 int userId) {
6732 synchronized (mGlobalLock) {
6733
6734 boolean didSomething =
6735 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006736 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006737 null, doit, evenPersistent, userId);
6738 return didSomething;
6739 }
6740 }
6741
6742 @Override
6743 public void resumeTopActivities(boolean scheduleIdle) {
6744 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006745 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 if (scheduleIdle) {
6747 mStackSupervisor.scheduleIdleLocked();
6748 }
6749 }
6750 }
6751
Riddle Hsua0536432019-02-16 00:38:59 +08006752 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006753 @Override
6754 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006755 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006756 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6757 }
6758 }
6759
Riddle Hsua0536432019-02-16 00:38:59 +08006760 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761 @Override
6762 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006763 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006764 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 }
6766 }
6767
6768 @Override
6769 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6770 try {
6771 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6772 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6773 }
6774 } catch (RemoteException ex) {
6775 throw new SecurityException("Fail to check is caller a privileged app", ex);
6776 }
6777
6778 synchronized (mGlobalLock) {
6779 final long ident = Binder.clearCallingIdentity();
6780 try {
6781 if (mAmInternal.shouldConfirmCredentials(userId)) {
6782 if (mKeyguardController.isKeyguardLocked()) {
6783 // Showing launcher to avoid user entering credential twice.
6784 startHomeActivity(currentUserId, "notifyLockedProfile");
6785 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006786 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 }
6788 } finally {
6789 Binder.restoreCallingIdentity(ident);
6790 }
6791 }
6792 }
6793
6794 @Override
6795 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6796 mAmInternal.enforceCallingPermission(
6797 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6798
6799 synchronized (mGlobalLock) {
6800 final long ident = Binder.clearCallingIdentity();
6801 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006802 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6803 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006804 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006805 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6806 UserHandle.CURRENT);
6807 } finally {
6808 Binder.restoreCallingIdentity(ident);
6809 }
6810 }
6811 }
6812
6813 @Override
6814 public void writeActivitiesToProto(ProtoOutputStream proto) {
6815 synchronized (mGlobalLock) {
6816 // The output proto of "activity --proto activities"
6817 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006818 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006819 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6820 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 }
6822 }
6823
6824 @Override
6825 public void saveANRState(String reason) {
6826 synchronized (mGlobalLock) {
6827 final StringWriter sw = new StringWriter();
6828 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6829 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6830 if (reason != null) {
6831 pw.println(" Reason: " + reason);
6832 }
6833 pw.println();
6834 getActivityStartController().dump(pw, " ", null);
6835 pw.println();
6836 pw.println("-------------------------------------------------------------------------------");
6837 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6838 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6839 "" /* header */);
6840 pw.println();
6841 pw.close();
6842
6843 mLastANRState = sw.toString();
6844 }
6845 }
6846
6847 @Override
6848 public void clearSavedANRState() {
6849 synchronized (mGlobalLock) {
6850 mLastANRState = null;
6851 }
6852 }
6853
6854 @Override
6855 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6856 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6857 synchronized (mGlobalLock) {
6858 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6859 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6860 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6861 dumpLastANRLocked(pw);
6862 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6863 dumpLastANRTracesLocked(pw);
6864 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6865 dumpActivityStarterLocked(pw, dumpPackage);
6866 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6867 dumpActivityContainersLocked(pw);
6868 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6869 if (getRecentTasks() != null) {
6870 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6871 }
6872 }
6873 }
6874 }
6875
6876 @Override
6877 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6878 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6879 int wakefulness) {
6880 synchronized (mGlobalLock) {
6881 if (mHomeProcess != null && (dumpPackage == null
6882 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6883 if (needSep) {
6884 pw.println();
6885 needSep = false;
6886 }
6887 pw.println(" mHomeProcess: " + mHomeProcess);
6888 }
6889 if (mPreviousProcess != null && (dumpPackage == null
6890 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6891 if (needSep) {
6892 pw.println();
6893 needSep = false;
6894 }
6895 pw.println(" mPreviousProcess: " + mPreviousProcess);
6896 }
6897 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6898 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6899 StringBuilder sb = new StringBuilder(128);
6900 sb.append(" mPreviousProcessVisibleTime: ");
6901 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6902 pw.println(sb);
6903 }
6904 if (mHeavyWeightProcess != null && (dumpPackage == null
6905 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6906 if (needSep) {
6907 pw.println();
6908 needSep = false;
6909 }
6910 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6911 }
6912 if (dumpPackage == null) {
6913 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006914 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 }
6916 if (dumpAll) {
6917 if (dumpPackage == null) {
6918 pw.println(" mConfigWillChange: "
6919 + getTopDisplayFocusedStack().mConfigWillChange);
6920 }
6921 if (mCompatModePackages.getPackages().size() > 0) {
6922 boolean printed = false;
6923 for (Map.Entry<String, Integer> entry
6924 : mCompatModePackages.getPackages().entrySet()) {
6925 String pkg = entry.getKey();
6926 int mode = entry.getValue();
6927 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6928 continue;
6929 }
6930 if (!printed) {
6931 pw.println(" mScreenCompatPackages:");
6932 printed = true;
6933 }
6934 pw.println(" " + pkg + ": " + mode);
6935 }
6936 }
6937 }
6938
6939 if (dumpPackage == null) {
6940 pw.println(" mWakefulness="
6941 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006942 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006943 if (mRunningVoice != null) {
6944 pw.println(" mRunningVoice=" + mRunningVoice);
6945 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6946 }
6947 pw.println(" mSleeping=" + mSleeping);
6948 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6949 pw.println(" mVrController=" + mVrController);
6950 }
6951 if (mCurAppTimeTracker != null) {
6952 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6953 }
6954 if (mAllowAppSwitchUids.size() > 0) {
6955 boolean printed = false;
6956 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6957 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6958 for (int j = 0; j < types.size(); j++) {
6959 if (dumpPackage == null ||
6960 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6961 if (needSep) {
6962 pw.println();
6963 needSep = false;
6964 }
6965 if (!printed) {
6966 pw.println(" mAllowAppSwitchUids:");
6967 printed = true;
6968 }
6969 pw.print(" User ");
6970 pw.print(mAllowAppSwitchUids.keyAt(i));
6971 pw.print(": Type ");
6972 pw.print(types.keyAt(j));
6973 pw.print(" = ");
6974 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6975 pw.println();
6976 }
6977 }
6978 }
6979 }
6980 if (dumpPackage == null) {
6981 if (mController != null) {
6982 pw.println(" mController=" + mController
6983 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6984 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006985 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6986 pw.println(" mLaunchingActivityWakeLock="
6987 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006988 }
6989
6990 return needSep;
6991 }
6992 }
6993
6994 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006995 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6996 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006997 synchronized (mGlobalLock) {
6998 if (dumpPackage == null) {
6999 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7000 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007001 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7002 if (mRunningVoice != null) {
7003 final long vrToken = proto.start(
7004 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7005 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7006 mRunningVoice.toString());
7007 mVoiceWakeLock.writeToProto(
7008 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7009 proto.end(vrToken);
7010 }
7011 mVrController.writeToProto(proto,
7012 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007013 if (mController != null) {
7014 final long token = proto.start(CONTROLLER);
7015 proto.write(CONTROLLER, mController.toString());
7016 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7017 proto.end(token);
7018 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007019 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7020 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7021 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007022 }
7023
7024 if (mHomeProcess != null && (dumpPackage == null
7025 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007026 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007027 }
7028
7029 if (mPreviousProcess != null && (dumpPackage == null
7030 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007031 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007032 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7033 }
7034
7035 if (mHeavyWeightProcess != null && (dumpPackage == null
7036 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007037 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 }
7039
7040 for (Map.Entry<String, Integer> entry
7041 : mCompatModePackages.getPackages().entrySet()) {
7042 String pkg = entry.getKey();
7043 int mode = entry.getValue();
7044 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7045 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7046 proto.write(PACKAGE, pkg);
7047 proto.write(MODE, mode);
7048 proto.end(compatToken);
7049 }
7050 }
7051
7052 if (mCurAppTimeTracker != null) {
7053 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7054 }
7055
7056 }
7057 }
7058
7059 @Override
7060 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7061 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7062 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007063 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7064 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007065 }
7066
7067 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007068 public void dumpForOom(PrintWriter pw) {
7069 synchronized (mGlobalLock) {
7070 pw.println(" mHomeProcess: " + mHomeProcess);
7071 pw.println(" mPreviousProcess: " + mPreviousProcess);
7072 if (mHeavyWeightProcess != null) {
7073 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7074 }
7075 }
7076 }
7077
7078 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007079 public boolean canGcNow() {
7080 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007081 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007082 }
7083 }
7084
Riddle Hsua0536432019-02-16 00:38:59 +08007085 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007086 @Override
7087 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007088 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007089 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007090 return top != null ? top.app : null;
7091 }
7092 }
7093
Riddle Hsua0536432019-02-16 00:38:59 +08007094 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007095 @Override
7096 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007097 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007098 if (mRootActivityContainer != null) {
7099 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 }
7101 }
7102 }
7103
7104 @Override
7105 public void scheduleDestroyAllActivities(String reason) {
7106 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007107 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007108 }
7109 }
7110
7111 @Override
7112 public void removeUser(int userId) {
7113 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007114 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007115 }
7116 }
7117
7118 @Override
7119 public boolean switchUser(int userId, UserState userState) {
7120 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007121 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 }
7123 }
7124
7125 @Override
7126 public void onHandleAppCrash(WindowProcessController wpc) {
7127 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007128 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 }
7130 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007131
7132 @Override
7133 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7134 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007135 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007136 }
7137 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007138
Riddle Hsua0536432019-02-16 00:38:59 +08007139 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007140 @Override
7141 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007142 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007143 }
7144
Riddle Hsua0536432019-02-16 00:38:59 +08007145 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007146 @Override
7147 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007148 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007149 }
7150
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007154 mActiveUids.onActiveUidsCleared();
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 onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007160 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007161 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007162
7163 @Override
7164 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007165 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007166 mPendingTempWhitelist.put(uid, tag);
7167 }
7168 }
7169
7170 @Override
7171 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007172 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007173 mPendingTempWhitelist.remove(uid);
7174 }
7175 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007176
7177 @Override
7178 public boolean handleAppCrashInActivityController(String processName, int pid,
7179 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7180 Runnable killCrashingAppCallback) {
7181 synchronized (mGlobalLock) {
7182 if (mController == null) {
7183 return false;
7184 }
7185
7186 try {
7187 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7188 stackTrace)) {
7189 killCrashingAppCallback.run();
7190 return true;
7191 }
7192 } catch (RemoteException e) {
7193 mController = null;
7194 Watchdog.getInstance().setActivityController(null);
7195 }
7196 return false;
7197 }
7198 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007199
7200 @Override
7201 public void removeRecentTasksByPackageName(String packageName, int userId) {
7202 synchronized (mGlobalLock) {
7203 mRecentTasks.removeTasksByPackageName(packageName, userId);
7204 }
7205 }
7206
7207 @Override
7208 public void cleanupRecentTasksForUser(int userId) {
7209 synchronized (mGlobalLock) {
7210 mRecentTasks.cleanupLocked(userId);
7211 }
7212 }
7213
7214 @Override
7215 public void loadRecentTasksForUser(int userId) {
7216 synchronized (mGlobalLock) {
7217 mRecentTasks.loadUserRecentsLocked(userId);
7218 }
7219 }
7220
7221 @Override
7222 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7223 synchronized (mGlobalLock) {
7224 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7225 }
7226 }
7227
7228 @Override
7229 public void flushRecentTasks() {
7230 mRecentTasks.flush();
7231 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007232
7233 @Override
7234 public WindowProcessController getHomeProcess() {
7235 synchronized (mGlobalLock) {
7236 return mHomeProcess;
7237 }
7238 }
7239
7240 @Override
7241 public WindowProcessController getPreviousProcess() {
7242 synchronized (mGlobalLock) {
7243 return mPreviousProcess;
7244 }
7245 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007246
7247 @Override
7248 public void clearLockedTasks(String reason) {
7249 synchronized (mGlobalLock) {
7250 getLockTaskController().clearLockedTasks(reason);
7251 }
7252 }
7253
7254 @Override
7255 public void updateUserConfiguration() {
7256 synchronized (mGlobalLock) {
7257 final Configuration configuration = new Configuration(getGlobalConfiguration());
7258 final int currentUserId = mAmInternal.getCurrentUserId();
7259 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7260 configuration, currentUserId, Settings.System.canWrite(mContext));
7261 updateConfigurationLocked(configuration, null /* starting */,
7262 false /* initLocale */, false /* persistent */, currentUserId,
7263 false /* deferResume */);
7264 }
7265 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007266
7267 @Override
7268 public boolean canShowErrorDialogs() {
7269 synchronized (mGlobalLock) {
7270 return mShowDialogs && !mSleeping && !mShuttingDown
7271 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7272 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7273 mAmInternal.getCurrentUserId())
7274 && !(UserManager.isDeviceInDemoMode(mContext)
7275 && mAmInternal.getCurrentUser().isDemo());
7276 }
7277 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007278
7279 @Override
7280 public void setProfileApp(String profileApp) {
7281 synchronized (mGlobalLock) {
7282 mProfileApp = profileApp;
7283 }
7284 }
7285
7286 @Override
7287 public void setProfileProc(WindowProcessController wpc) {
7288 synchronized (mGlobalLock) {
7289 mProfileProc = wpc;
7290 }
7291 }
7292
7293 @Override
7294 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7295 synchronized (mGlobalLock) {
7296 mProfilerInfo = profilerInfo;
7297 }
7298 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007299
7300 @Override
7301 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7302 synchronized (mGlobalLock) {
7303 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7304 }
7305 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007306
7307 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007308 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7309 boolean reducedResolution) {
7310 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7311 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007312 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007313
7314 @Override
7315 public boolean isUidForeground(int uid) {
7316 synchronized (mGlobalLock) {
7317 return ActivityTaskManagerService.this.isUidForeground(uid);
7318 }
7319 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007320
7321 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007322 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007323 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007324 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007325 }
7326 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007327
7328 @Override
7329 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007330 // Translate package names into UIDs
7331 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007332 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007333 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7334 if (uid >= 0) {
7335 result.add(uid);
7336 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007337 }
7338 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007339 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007340 }
7341 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007342 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007343}