blob: ee56c0902e780e8b3fbb106f466c811d7585b2fb [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;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100214import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700247import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.server.LocalServices;
249import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700250import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800251import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700253import com.android.server.am.ActivityManagerService;
254import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
255import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
256import com.android.server.am.AppTimeTracker;
257import com.android.server.am.BaseErrorDialog;
258import com.android.server.am.EventLogTags;
259import com.android.server.am.PendingIntentController;
260import com.android.server.am.PendingIntentRecord;
261import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900262import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700263import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700264import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800266import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800278import java.lang.annotation.ElementType;
279import java.lang.annotation.Retention;
280import java.lang.annotation.RetentionPolicy;
281import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700285import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400287import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700290import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Map;
292import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293
294/**
295 * System service for managing activities and their containers (task, stacks, displays,... ).
296 *
297 * {@hide}
298 */
299public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700300 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700302 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
303 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
304 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
305 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
306 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700307 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100313 // How long we permit background activity starts after an activity in the process
314 // started or finished.
315 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316
Wale Ogunwale98875612018-10-12 07:53:02 -0700317 /** Used to indicate that an app transition should be animated. */
318 static final boolean ANIMATE = true;
319
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700320 /** Hardware-reported OpenGLES version. */
321 final int GL_ES_VERSION;
322
Wale Ogunwale31913b52018-10-13 08:29:31 -0700323 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
324 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
325 public static final String DUMP_LASTANR_CMD = "lastanr" ;
326 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
327 public static final String DUMP_STARTER_CMD = "starter" ;
328 public static final String DUMP_CONTAINERS_CMD = "containers" ;
329 public static final String DUMP_RECENTS_CMD = "recents" ;
330 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
331
Wale Ogunwale64258362018-10-16 15:13:37 -0700332 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
333 public static final int RELAUNCH_REASON_NONE = 0;
334 /** This activity is being relaunched due to windowing mode change. */
335 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
336 /** This activity is being relaunched due to a free-resize operation. */
337 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
338
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700339 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700340
Wale Ogunwalef6733932018-06-27 05:14:34 -0700341 /**
342 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
343 * change at runtime. Use mContext for non-UI purposes.
344 */
345 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700347 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700350 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700351 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800352 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800353 @VisibleForTesting
354 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 PowerManagerInternal mPowerManagerInternal;
356 private UsageStatsManagerInternal mUsageStatsInternal;
357
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700358 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 IntentFirewall mIntentFirewall;
360
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700361 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800362 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800363 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700364 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
366 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
367 *
368 * @see WindowManagerThreadPriorityBooster
369 */
370 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700371 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800372 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700373 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700374 private UserManagerService mUserManager;
375 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700376 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800377 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700378 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /** All processes currently running that might have a window organized by name. */
380 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100381 /** All processes we currently have running mapped by pid and uid */
382 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** This is the process holding what we currently consider to be the "home" activity. */
384 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700385 /** The currently running heavy-weight process, if any. */
386 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700387 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /**
389 * This is the process holding the activity the user last visited that is in a different process
390 * from the one they are currently in.
391 */
392 WindowProcessController mPreviousProcess;
393 /** The time at which the previous process was last visible. */
394 long mPreviousProcessVisibleTime;
395
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700396 /** List of intents that were used to start the most recent tasks. */
397 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700398 /** State of external calls telling us if the device is awake or asleep. */
399 private boolean mKeyguardShown = false;
400
401 // Wrapper around VoiceInteractionServiceManager
402 private AssistUtils mAssistUtils;
403
404 // VoiceInteraction session ID that changes for each new request except when
405 // being called for multi-window assist in a single session.
406 private int mViSessionId = 1000;
407
408 // How long to wait in getAssistContextExtras for the activity and foreground services
409 // to respond with the result.
410 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
411
412 // How long top wait when going through the modern assist (which doesn't need to block
413 // on getting this result before starting to launch its UI).
414 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
415
416 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
417 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
418
Alison Cichowlas3e340502018-08-07 17:15:01 -0400419 // Permission tokens are used to temporarily granted a trusted app the ability to call
420 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
421 // showing any appropriate error messages to the user.
422 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
423 10 * MINUTE_IN_MILLIS;
424
425 // How long before the service actually expires a token. This is slightly longer than
426 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
427 // expiration exception.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
429 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
430
431 // How long the service will remember expired tokens, for the purpose of providing error
432 // messaging when a client uses an expired token.
433 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
434 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
435
436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700462 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
Ricky Wai906af482019-06-03 17:25:28 +0100507 /**
508 * Last stop app switches time, apps finished before this time cannot start background activity
509 * even if they are in grace period.
510 */
511 private long mLastStopAppSwitchesTime;
512
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 IActivityController mController = null;
514 boolean mControllerIsAMonkey = false;
515
Wale Ogunwale214f3482018-10-04 11:00:47 -0700516 final int mFactoryTest;
517
518 /** Used to control how we initialize the service. */
519 ComponentName mTopComponent;
520 String mTopAction = Intent.ACTION_MAIN;
521 String mTopData;
522
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800523 /** Profiling app information. */
524 String mProfileApp = null;
525 WindowProcessController mProfileProc = null;
526 ProfilerInfo mProfilerInfo = null;
527
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700528 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700529 * Dump of the activity state at the time of the last ANR. Cleared after
530 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
531 */
532 String mLastANRState;
533
534 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 * Used to retain an update lock when the foreground activity is in
536 * immersive mode.
537 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700538 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539
540 /**
541 * Packages that are being allowed to perform unrestricted app switches. Mapping is
542 * User -> Type -> uid.
543 */
544 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
545
546 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700547 private int mThumbnailWidth;
548 private int mThumbnailHeight;
549 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700550
551 /**
552 * Flag that indicates if multi-window is enabled.
553 *
554 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
555 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
556 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
557 * At least one of the forms of multi-window must be enabled in order for this flag to be
558 * initialized to 'true'.
559 *
560 * @see #mSupportsSplitScreenMultiWindow
561 * @see #mSupportsFreeformWindowManagement
562 * @see #mSupportsPictureInPicture
563 * @see #mSupportsMultiDisplay
564 */
565 boolean mSupportsMultiWindow;
566 boolean mSupportsSplitScreenMultiWindow;
567 boolean mSupportsFreeformWindowManagement;
568 boolean mSupportsPictureInPicture;
569 boolean mSupportsMultiDisplay;
570 boolean mForceResizableActivities;
571
572 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
573
574 // VR Vr2d Display Id.
575 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700576
Wale Ogunwalef6733932018-06-27 05:14:34 -0700577 /**
578 * Set while we are wanting to sleep, to prevent any
579 * activities from being started/resumed.
580 *
581 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
582 *
583 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
584 * while in the sleep state until there is a pending transition out of sleep, in which case
585 * mSleeping is set to false, and remains false while awake.
586 *
587 * Whether mSleeping can quickly toggled between true/false without the device actually
588 * display changing states is undefined.
589 */
590 private boolean mSleeping = false;
591
592 /**
593 * The process state used for processes that are running the top activities.
594 * This changes between TOP and TOP_SLEEPING to following mSleeping.
595 */
596 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
597
598 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
599 // automatically. Important for devices without direct input devices.
600 private boolean mShowDialogs = true;
601
602 /** Set if we are shutting down the system, similar to sleeping. */
603 boolean mShuttingDown = false;
604
605 /**
606 * We want to hold a wake lock while running a voice interaction session, since
607 * this may happen with the screen off and we need to keep the CPU running to
608 * be able to continue to interact with the user.
609 */
610 PowerManager.WakeLock mVoiceWakeLock;
611
612 /**
613 * Set while we are running a voice interaction. This overrides sleeping while it is active.
614 */
615 IVoiceInteractionSession mRunningVoice;
616
617 /**
618 * The last resumed activity. This is identical to the current resumed activity most
619 * of the time but could be different when we're pausing one activity before we resume
620 * another activity.
621 */
622 ActivityRecord mLastResumedActivity;
623
624 /**
625 * The activity that is currently being traced as the active resumed activity.
626 *
627 * @see #updateResumedAppTrace
628 */
629 private @Nullable ActivityRecord mTracedResumedActivity;
630
631 /** If non-null, we are tracking the time the user spends in the currently focused app. */
632 AppTimeTracker mCurAppTimeTracker;
633
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700634 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700635
Wale Ogunwale53783742018-09-16 10:21:51 -0700636 /**
637 * Packages that the user has asked to have run in screen size
638 * compatibility mode instead of filling the screen.
639 */
640 CompatModePackages mCompatModePackages;
641
Wale Ogunwalef6733932018-06-27 05:14:34 -0700642 private FontScaleSettingObserver mFontScaleSettingObserver;
643
Ricky Wai96f5c352019-04-10 18:40:17 +0100644 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private final class FontScaleSettingObserver extends ContentObserver {
647 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
648 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
649
650 public FontScaleSettingObserver() {
651 super(mH);
652 final ContentResolver resolver = mContext.getContentResolver();
653 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
654 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
655 UserHandle.USER_ALL);
656 }
657
658 @Override
659 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
660 if (mFontScaleUri.equals(uri)) {
661 updateFontScaleIfNeeded(userId);
662 } else if (mHideErrorDialogsUri.equals(uri)) {
663 synchronized (mGlobalLock) {
664 updateShouldShowDialogsLocked(getGlobalConfiguration());
665 }
666 }
667 }
668 }
669
Riddle Hsua0536432019-02-16 00:38:59 +0800670 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
671 @Target(ElementType.METHOD)
672 @Retention(RetentionPolicy.SOURCE)
673 @interface HotPath {
674 int NONE = 0;
675 int OOM_ADJUSTMENT = 1;
676 int LRU_UPDATE = 2;
677 int PROCESS_CHANGE = 3;
678 int caller() default NONE;
679 }
680
Charles Chen8d98dd22018-12-26 17:36:54 +0800681 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
682 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700683 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700684 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700685 mSystemThread = ActivityThread.currentActivityThread();
686 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700687 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800688 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700690 }
691
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700692 public void onSystemReady() {
693 synchronized (mGlobalLock) {
694 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
695 PackageManager.FEATURE_CANT_SAVE_STATE);
696 mAssistUtils = new AssistUtils(mContext);
697 mVrController.onSystemReady();
698 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700699 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700700 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700701 }
702
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700703 public void onInitPowerManagement() {
704 synchronized (mGlobalLock) {
705 mStackSupervisor.initPowerManagement();
706 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
707 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
708 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
709 mVoiceWakeLock.setReferenceCounted(false);
710 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700711 }
712
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700713 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700714 mFontScaleSettingObserver = new FontScaleSettingObserver();
715 }
716
Wale Ogunwale59507092018-10-29 09:00:30 -0700717 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700718 final boolean freeformWindowManagement =
719 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
720 || Settings.Global.getInt(
721 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
722
723 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
724 final boolean supportsPictureInPicture = supportsMultiWindow &&
725 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
726 final boolean supportsSplitScreenMultiWindow =
727 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
728 final boolean supportsMultiDisplay = mContext.getPackageManager()
729 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
731 final boolean forceResizable = Settings.Global.getInt(
732 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
733
734 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900735 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700736
737 final Configuration configuration = new Configuration();
738 Settings.System.getConfiguration(resolver, configuration);
739 if (forceRtl) {
740 // This will take care of setting the correct layout direction flags
741 configuration.setLayoutDirection(configuration.locale);
742 }
743
744 synchronized (mGlobalLock) {
745 mForceResizableActivities = forceResizable;
746 final boolean multiWindowFormEnabled = freeformWindowManagement
747 || supportsSplitScreenMultiWindow
748 || supportsPictureInPicture
749 || supportsMultiDisplay;
750 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
751 mSupportsMultiWindow = true;
752 mSupportsFreeformWindowManagement = freeformWindowManagement;
753 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
754 mSupportsPictureInPicture = supportsPictureInPicture;
755 mSupportsMultiDisplay = supportsMultiDisplay;
756 } else {
757 mSupportsMultiWindow = false;
758 mSupportsFreeformWindowManagement = false;
759 mSupportsSplitScreenMultiWindow = false;
760 mSupportsPictureInPicture = false;
761 mSupportsMultiDisplay = false;
762 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700763 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700764 // This happens before any activities are started, so we can change global configuration
765 // in-place.
766 updateConfigurationLocked(configuration, null, true);
767 final Configuration globalConfig = getGlobalConfiguration();
768 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
769
770 // Load resources only after the current configuration has been set.
771 final Resources res = mContext.getResources();
772 mThumbnailWidth = res.getDimensionPixelSize(
773 com.android.internal.R.dimen.thumbnail_width);
774 mThumbnailHeight = res.getDimensionPixelSize(
775 com.android.internal.R.dimen.thumbnail_height);
776
777 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
778 mFullscreenThumbnailScale = (float) res
779 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
780 (float) globalConfig.screenWidthDp;
781 } else {
782 mFullscreenThumbnailScale = res.getFraction(
783 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
784 }
785 }
786 }
787
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800788 public WindowManagerGlobalLock getGlobalLock() {
789 return mGlobalLock;
790 }
791
Yunfan Chen585f2932019-01-29 16:04:45 +0900792 /** For test purpose only. */
793 @VisibleForTesting
794 public ActivityTaskManagerInternal getAtmInternal() {
795 return mInternal;
796 }
797
Riddle Hsud93a6c42018-11-29 21:50:06 +0800798 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
799 Looper looper) {
800 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700801 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700802 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700803 final File systemDir = SystemServiceManager.ensureSystemDir();
804 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
805 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700806 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700807
808 mTempConfig.setToDefaults();
809 mTempConfig.setLocales(LocaleList.getDefault());
810 mConfigurationSeq = mTempConfig.seq = 1;
811 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800812 mRootActivityContainer = new RootActivityContainer(this);
813 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700814
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700815 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700816 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700817 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700818 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700819 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700820 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700821 mKeyguardController = mStackSupervisor.getKeyguardController();
822 }
823
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700824 public void onActivityManagerInternalAdded() {
825 synchronized (mGlobalLock) {
826 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
827 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
828 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700829 }
830
Yunfan Chen75157d72018-07-27 14:47:21 +0900831 int increaseConfigurationSeqLocked() {
832 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
833 return mConfigurationSeq;
834 }
835
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700836 protected ActivityStackSupervisor createStackSupervisor() {
837 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
838 supervisor.initialize();
839 return supervisor;
840 }
841
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700842 public void setWindowManager(WindowManagerService wm) {
843 synchronized (mGlobalLock) {
844 mWindowManager = wm;
845 mLockTaskController.setWindowManager(wm);
846 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800847 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700849 }
850
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700851 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
852 synchronized (mGlobalLock) {
853 mUsageStatsInternal = usageStatsManager;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 }
856
Wale Ogunwalef6733932018-06-27 05:14:34 -0700857 UserManagerService getUserManager() {
858 if (mUserManager == null) {
859 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
860 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
861 }
862 return mUserManager;
863 }
864
865 AppOpsService getAppOpsService() {
866 if (mAppOpsService == null) {
867 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
868 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
869 }
870 return mAppOpsService;
871 }
872
873 boolean hasUserRestriction(String restriction, int userId) {
874 return getUserManager().hasUserRestriction(restriction, userId);
875 }
876
Michal Karpinski15486842019-04-25 17:33:42 +0100877 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
878 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
879 callingUid, callingPackage);
880 if (mode == AppOpsManager.MODE_DEFAULT) {
881 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
882 == PERMISSION_GRANTED;
883 }
884 return mode == AppOpsManager.MODE_ALLOWED;
885 }
886
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700887 @VisibleForTesting
888 protected void setRecentTasks(RecentTasks recentTasks) {
889 mRecentTasks = recentTasks;
890 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700891 }
892
893 RecentTasks getRecentTasks() {
894 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700895 }
896
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700897 ClientLifecycleManager getLifecycleManager() {
898 return mLifecycleManager;
899 }
900
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700901 ActivityStartController getActivityStartController() {
902 return mActivityStartController;
903 }
904
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700905 TaskChangeNotificationController getTaskChangeNotificationController() {
906 return mTaskChangeNotificationController;
907 }
908
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700909 LockTaskController getLockTaskController() {
910 return mLockTaskController;
911 }
912
Yunfan Chen75157d72018-07-27 14:47:21 +0900913 /**
914 * Return the global configuration used by the process corresponding to the input pid. This is
915 * usually the global configuration with some overrides specific to that process.
916 */
917 Configuration getGlobalConfigurationForCallingPid() {
918 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800919 return getGlobalConfigurationForPid(pid);
920 }
921
922 /**
923 * Return the global configuration used by the process corresponding to the given pid.
924 */
925 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900926 if (pid == MY_PID || pid < 0) {
927 return getGlobalConfiguration();
928 }
929 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100930 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900931 return app != null ? app.getConfiguration() : getGlobalConfiguration();
932 }
933 }
934
935 /**
936 * Return the device configuration info used by the process corresponding to the input pid.
937 * The value is consistent with the global configuration for the process.
938 */
939 @Override
940 public ConfigurationInfo getDeviceConfigurationInfo() {
941 ConfigurationInfo config = new ConfigurationInfo();
942 synchronized (mGlobalLock) {
943 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
944 config.reqTouchScreen = globalConfig.touchscreen;
945 config.reqKeyboardType = globalConfig.keyboard;
946 config.reqNavigation = globalConfig.navigation;
947 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
948 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
949 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
950 }
951 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
952 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
954 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700955 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900956 }
957 return config;
958 }
959
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700960 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700961 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700962 }
963
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700964 public static final class Lifecycle extends SystemService {
965 private final ActivityTaskManagerService mService;
966
967 public Lifecycle(Context context) {
968 super(context);
969 mService = new ActivityTaskManagerService(context);
970 }
971
972 @Override
973 public void onStart() {
974 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700975 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700976 }
977
Garfield Tan891146c2018-10-09 12:14:00 -0700978 @Override
979 public void onUnlockUser(int userId) {
980 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800981 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700982 }
983 }
984
985 @Override
986 public void onCleanupUser(int userId) {
987 synchronized (mService.getGlobalLock()) {
988 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
989 }
990 }
991
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700992 public ActivityTaskManagerService getService() {
993 return mService;
994 }
995 }
996
997 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700998 public final int startActivity(IApplicationThread caller, String callingPackage,
999 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1000 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1001 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1002 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1003 UserHandle.getCallingUserId());
1004 }
1005
1006 @Override
1007 public final int startActivities(IApplicationThread caller, String callingPackage,
1008 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1009 int userId) {
1010 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001011 enforceNotIsolatedCaller(reason);
1012 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001014 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1015 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1016 reason, null /* originatingPendingIntent */,
1017 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001018 }
1019
1020 @Override
1021 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1022 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1023 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1024 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1025 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1026 true /*validateIncomingUser*/);
1027 }
1028
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001029 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1031 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1032 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001033 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001035 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1037
1038 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001039 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 .setCaller(caller)
1041 .setCallingPackage(callingPackage)
1042 .setResolvedType(resolvedType)
1043 .setResultTo(resultTo)
1044 .setResultWho(resultWho)
1045 .setRequestCode(requestCode)
1046 .setStartFlags(startFlags)
1047 .setProfilerInfo(profilerInfo)
1048 .setActivityOptions(bOptions)
1049 .setMayWait(userId)
1050 .execute();
1051
1052 }
1053
1054 @Override
1055 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1056 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1058 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001059 // Refuse possible leaked file descriptors
1060 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1061 throw new IllegalArgumentException("File descriptors passed in Intent");
1062 }
1063
1064 if (!(target instanceof PendingIntentRecord)) {
1065 throw new IllegalArgumentException("Bad PendingIntent object");
1066 }
1067
1068 PendingIntentRecord pir = (PendingIntentRecord)target;
1069
1070 synchronized (mGlobalLock) {
1071 // If this is coming from the currently resumed activity, it is
1072 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001073 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 if (stack.mResumedActivity != null &&
1075 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001076 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001077 }
1078 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001079 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 }
1082
1083 @Override
1084 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1085 Bundle bOptions) {
1086 // Refuse possible leaked file descriptors
1087 if (intent != null && intent.hasFileDescriptors()) {
1088 throw new IllegalArgumentException("File descriptors passed in Intent");
1089 }
1090 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1091
1092 synchronized (mGlobalLock) {
1093 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1094 if (r == null) {
1095 SafeActivityOptions.abort(options);
1096 return false;
1097 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001098 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001099 // The caller is not running... d'oh!
1100 SafeActivityOptions.abort(options);
1101 return false;
1102 }
1103 intent = new Intent(intent);
1104 // The caller is not allowed to change the data.
1105 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1106 // And we are resetting to find the next component...
1107 intent.setComponent(null);
1108
1109 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1110
1111 ActivityInfo aInfo = null;
1112 try {
1113 List<ResolveInfo> resolves =
1114 AppGlobals.getPackageManager().queryIntentActivities(
1115 intent, r.resolvedType,
1116 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1117 UserHandle.getCallingUserId()).getList();
1118
1119 // Look for the original activity in the list...
1120 final int N = resolves != null ? resolves.size() : 0;
1121 for (int i=0; i<N; i++) {
1122 ResolveInfo rInfo = resolves.get(i);
1123 if (rInfo.activityInfo.packageName.equals(r.packageName)
1124 && rInfo.activityInfo.name.equals(r.info.name)) {
1125 // We found the current one... the next matching is
1126 // after it.
1127 i++;
1128 if (i<N) {
1129 aInfo = resolves.get(i).activityInfo;
1130 }
1131 if (debug) {
1132 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1133 + "/" + r.info.name);
1134 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1135 ? "null" : aInfo.packageName + "/" + aInfo.name));
1136 }
1137 break;
1138 }
1139 }
1140 } catch (RemoteException e) {
1141 }
1142
1143 if (aInfo == null) {
1144 // Nobody who is next!
1145 SafeActivityOptions.abort(options);
1146 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1147 return false;
1148 }
1149
1150 intent.setComponent(new ComponentName(
1151 aInfo.applicationInfo.packageName, aInfo.name));
1152 intent.setFlags(intent.getFlags()&~(
1153 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1154 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1155 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1156 FLAG_ACTIVITY_NEW_TASK));
1157
1158 // Okay now we need to start the new activity, replacing the currently running activity.
1159 // This is a little tricky because we want to start the new one as if the current one is
1160 // finished, but not finish the current one first so that there is no flicker.
1161 // And thus...
1162 final boolean wasFinishing = r.finishing;
1163 r.finishing = true;
1164
1165 // Propagate reply information over to the new activity.
1166 final ActivityRecord resultTo = r.resultTo;
1167 final String resultWho = r.resultWho;
1168 final int requestCode = r.requestCode;
1169 r.resultTo = null;
1170 if (resultTo != null) {
1171 resultTo.removeResultsLocked(r, resultWho, requestCode);
1172 }
1173
1174 final long origId = Binder.clearCallingIdentity();
1175 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001176 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001177 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001178 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001179 .setResolvedType(r.resolvedType)
1180 .setActivityInfo(aInfo)
1181 .setResultTo(resultTo != null ? resultTo.appToken : null)
1182 .setResultWho(resultWho)
1183 .setRequestCode(requestCode)
1184 .setCallingPid(-1)
1185 .setCallingUid(r.launchedFromUid)
1186 .setCallingPackage(r.launchedFromPackage)
1187 .setRealCallingPid(-1)
1188 .setRealCallingUid(r.launchedFromUid)
1189 .setActivityOptions(options)
1190 .execute();
1191 Binder.restoreCallingIdentity(origId);
1192
1193 r.finishing = wasFinishing;
1194 if (res != ActivityManager.START_SUCCESS) {
1195 return false;
1196 }
1197 return true;
1198 }
1199 }
1200
1201 @Override
1202 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1203 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1204 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1205 final WaitResult res = new WaitResult();
1206 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001207 enforceNotIsolatedCaller("startActivityAndWait");
1208 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1209 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001210 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001211 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 .setCaller(caller)
1213 .setCallingPackage(callingPackage)
1214 .setResolvedType(resolvedType)
1215 .setResultTo(resultTo)
1216 .setResultWho(resultWho)
1217 .setRequestCode(requestCode)
1218 .setStartFlags(startFlags)
1219 .setActivityOptions(bOptions)
1220 .setMayWait(userId)
1221 .setProfilerInfo(profilerInfo)
1222 .setWaitResult(res)
1223 .execute();
1224 }
1225 return res;
1226 }
1227
1228 @Override
1229 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1230 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1231 int startFlags, Configuration config, Bundle bOptions, int userId) {
1232 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001233 enforceNotIsolatedCaller("startActivityWithConfig");
1234 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1235 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001236 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001237 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 .setCaller(caller)
1239 .setCallingPackage(callingPackage)
1240 .setResolvedType(resolvedType)
1241 .setResultTo(resultTo)
1242 .setResultWho(resultWho)
1243 .setRequestCode(requestCode)
1244 .setStartFlags(startFlags)
1245 .setGlobalConfiguration(config)
1246 .setActivityOptions(bOptions)
1247 .setMayWait(userId)
1248 .execute();
1249 }
1250 }
1251
Alison Cichowlas3e340502018-08-07 17:15:01 -04001252
1253 @Override
1254 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1255 int callingUid = Binder.getCallingUid();
1256 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1257 throw new SecurityException("Only the system process can request a permission token, "
1258 + "received request from uid: " + callingUid);
1259 }
1260 IBinder permissionToken = new Binder();
1261 synchronized (mGlobalLock) {
1262 mStartActivitySources.put(permissionToken, delegatorToken);
1263 }
1264
1265 Message expireMsg = PooledLambda.obtainMessage(
1266 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1267 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1268
1269 Message forgetMsg = PooledLambda.obtainMessage(
1270 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1271 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1272
1273 return permissionToken;
1274 }
1275
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 @Override
1277 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1278 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1280 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001282 // permission grants) as any app that may launch one of your own activities. So we only
1283 // allow this in two cases:
1284 // 1) The caller is an activity that is part of the core framework, and then only when it
1285 // is running as the system.
1286 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1287 // can only be requested by a system activity, which may then delegate this call to
1288 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 final ActivityRecord sourceRecord;
1290 final int targetUid;
1291 final String targetPackage;
1292 final boolean isResolver;
1293 synchronized (mGlobalLock) {
1294 if (resultTo == null) {
1295 throw new SecurityException("Must be called from an activity");
1296 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001297 final IBinder sourceToken;
1298 if (permissionToken != null) {
1299 // To even attempt to use a permissionToken, an app must also have this signature
1300 // permission.
1301 mAmInternal.enforceCallingPermission(
1302 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1303 "startActivityAsCaller");
1304 // If called with a permissionToken, we want the sourceRecord from the delegator
1305 // activity that requested this token.
1306 sourceToken = mStartActivitySources.remove(permissionToken);
1307 if (sourceToken == null) {
1308 // Invalid permissionToken, check if it recently expired.
1309 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1310 throw new SecurityException("Called with expired permission token: "
1311 + permissionToken);
1312 } else {
1313 throw new SecurityException("Called with invalid permission token: "
1314 + permissionToken);
1315 }
1316 }
1317 } else {
1318 // This method was called directly by the source.
1319 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001321
Wale Ogunwaled32da472018-11-16 07:19:28 -08001322 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001323 if (sourceRecord == null) {
1324 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 }
1326 if (sourceRecord.app == null) {
1327 throw new SecurityException("Called without a process attached to activity");
1328 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001329
1330 // Whether called directly or from a delegate, the source activity must be from the
1331 // android package.
1332 if (!sourceRecord.info.packageName.equals("android")) {
1333 throw new SecurityException("Must be called from an activity that is "
1334 + "declared in the android package");
1335 }
1336
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001337 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 // This is still okay, as long as this activity is running under the
1339 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001340 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001341 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001342 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 + " must be system uid or original calling uid "
1344 + sourceRecord.launchedFromUid);
1345 }
1346 }
1347 if (ignoreTargetSecurity) {
1348 if (intent.getComponent() == null) {
1349 throw new SecurityException(
1350 "Component must be specified with ignoreTargetSecurity");
1351 }
1352 if (intent.getSelector() != null) {
1353 throw new SecurityException(
1354 "Selector not allowed with ignoreTargetSecurity");
1355 }
1356 }
1357 targetUid = sourceRecord.launchedFromUid;
1358 targetPackage = sourceRecord.launchedFromPackage;
1359 isResolver = sourceRecord.isResolverOrChildActivity();
1360 }
1361
1362 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001363 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 }
1365
1366 // TODO: Switch to user app stacks here.
1367 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001368 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 .setCallingUid(targetUid)
1370 .setCallingPackage(targetPackage)
1371 .setResolvedType(resolvedType)
1372 .setResultTo(resultTo)
1373 .setResultWho(resultWho)
1374 .setRequestCode(requestCode)
1375 .setStartFlags(startFlags)
1376 .setActivityOptions(bOptions)
1377 .setMayWait(userId)
1378 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1379 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001380 // The target may well be in the background, which would normally prevent it
1381 // from starting an activity. Here we definitely want the start to succeed.
1382 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001383 .execute();
1384 } catch (SecurityException e) {
1385 // XXX need to figure out how to propagate to original app.
1386 // A SecurityException here is generally actually a fault of the original
1387 // calling activity (such as a fairly granting permissions), so propagate it
1388 // back to them.
1389 /*
1390 StringBuilder msg = new StringBuilder();
1391 msg.append("While launching");
1392 msg.append(intent.toString());
1393 msg.append(": ");
1394 msg.append(e.getMessage());
1395 */
1396 throw e;
1397 }
1398 }
1399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1401 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1402 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1403 }
1404
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 @Override
1406 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1407 Intent intent, String resolvedType, IVoiceInteractionSession session,
1408 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1409 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 if (session == null || interactor == null) {
1412 throw new NullPointerException("null session or interactor");
1413 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001414 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001416 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 .setCallingUid(callingUid)
1418 .setCallingPackage(callingPackage)
1419 .setResolvedType(resolvedType)
1420 .setVoiceSession(session)
1421 .setVoiceInteractor(interactor)
1422 .setStartFlags(startFlags)
1423 .setProfilerInfo(profilerInfo)
1424 .setActivityOptions(bOptions)
1425 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001426 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001427 .execute();
1428 }
1429
1430 @Override
1431 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1432 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001433 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1434 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001435
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001436 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .setCallingUid(callingUid)
1438 .setCallingPackage(callingPackage)
1439 .setResolvedType(resolvedType)
1440 .setActivityOptions(bOptions)
1441 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001442 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001443 .execute();
1444 }
1445
Riddle Hsu609a8e22019-06-27 16:46:29 -06001446 /**
1447 * Start the recents activity to perform the recents animation.
1448 *
1449 * @param intent The intent to start the recents activity.
1450 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1451 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001453 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1454 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001457 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 final long origId = Binder.clearCallingIdentity();
1459 try {
1460 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001461 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1462 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001463 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464
1465 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001466 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001467 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001468 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 if (recentsAnimationRunner == null) {
1470 anim.preloadRecentsActivity();
1471 } else {
1472 anim.startRecentsActivity(recentsAnimationRunner);
1473 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001474 }
1475 } finally {
1476 Binder.restoreCallingIdentity(origId);
1477 }
1478 }
1479
1480 @Override
1481 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001482 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001483 "startActivityFromRecents()");
1484
1485 final int callingPid = Binder.getCallingPid();
1486 final int callingUid = Binder.getCallingUid();
1487 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1488 final long origId = Binder.clearCallingIdentity();
1489 try {
1490 synchronized (mGlobalLock) {
1491 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1492 safeOptions);
1493 }
1494 } finally {
1495 Binder.restoreCallingIdentity(origId);
1496 }
1497 }
1498
1499 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001500 * Public API to check if the client is allowed to start an activity on specified display.
1501 *
1502 * If the target display is private or virtual, some restrictions will apply.
1503 *
1504 * @param displayId Target display id.
1505 * @param intent Intent used to launch the activity.
1506 * @param resolvedType The MIME type of the intent.
1507 * @param userId The id of the user for whom the call is made.
1508 * @return {@code true} if a call to start an activity on the target display should succeed and
1509 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1510 */
1511 @Override
1512 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1513 String resolvedType, int userId) {
1514 final int callingUid = Binder.getCallingUid();
1515 final int callingPid = Binder.getCallingPid();
1516 final long origId = Binder.clearCallingIdentity();
1517
1518 try {
1519 // Collect information about the target of the Intent.
1520 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1521 0 /* startFlags */, null /* profilerInfo */, userId,
1522 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1523 UserHandle.USER_NULL));
1524 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1525
1526 synchronized (mGlobalLock) {
1527 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1528 aInfo);
1529 }
1530 } finally {
1531 Binder.restoreCallingIdentity(origId);
1532 }
1533 }
1534
1535 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001536 * This is the internal entry point for handling Activity.finish().
1537 *
1538 * @param token The Binder token referencing the Activity we want to finish.
1539 * @param resultCode Result code, if any, from this Activity.
1540 * @param resultData Result data (Intent), if any, from this Activity.
1541 * @param finishTask Whether to finish the task associated with this Activity.
1542 *
1543 * @return Returns true if the activity successfully finished, or false if it is still running.
1544 */
1545 @Override
1546 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1547 int finishTask) {
1548 // Refuse possible leaked file descriptors
1549 if (resultData != null && resultData.hasFileDescriptors()) {
1550 throw new IllegalArgumentException("File descriptors passed in Intent");
1551 }
1552
1553 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001554 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 if (r == null) {
1556 return true;
1557 }
1558 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001559 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001560 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001561 if (rootR == null) {
1562 Slog.w(TAG, "Finishing task with all activities already finished");
1563 }
1564 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1565 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001566 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 return false;
1568 }
1569
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001570 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1571 // We should consolidate.
1572 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001573 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001574 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 if (next != null) {
1576 // ask watcher if this is allowed
1577 boolean resumeOK = true;
1578 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001579 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001581 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 Watchdog.getInstance().setActivityController(null);
1583 }
1584
1585 if (!resumeOK) {
1586 Slog.i(TAG, "Not finishing activity because controller resumed");
1587 return false;
1588 }
1589 }
1590 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001591
1592 // note down that the process has finished an activity and is in background activity
1593 // starts grace period
1594 if (r.app != null) {
1595 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1596 }
1597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 final long origId = Binder.clearCallingIdentity();
1599 try {
1600 boolean res;
1601 final boolean finishWithRootActivity =
1602 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1603 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1604 || (finishWithRootActivity && r == rootR)) {
1605 // If requested, remove the task that is associated to this activity only if it
1606 // was the root activity in the task. The result code and data is ignored
1607 // because we don't support returning them across task boundaries. Also, to
1608 // keep backwards compatibility we remove the task from recents when finishing
1609 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001610 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001611 finishWithRootActivity, "finish-activity");
1612 if (!res) {
1613 Slog.i(TAG, "Removing task failed to finish activity");
1614 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001615 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001616 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001617 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001618 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001619 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 if (!res) {
1621 Slog.i(TAG, "Failed to finish by app-request");
1622 }
1623 }
1624 return res;
1625 } finally {
1626 Binder.restoreCallingIdentity(origId);
1627 }
1628 }
1629 }
1630
1631 @Override
1632 public boolean finishActivityAffinity(IBinder token) {
1633 synchronized (mGlobalLock) {
1634 final long origId = Binder.clearCallingIdentity();
1635 try {
1636 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1637 if (r == null) {
1638 return false;
1639 }
1640
1641 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1642 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001643 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001644 return false;
1645 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001646 r.finishActivityAffinity();
1647 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 } finally {
1649 Binder.restoreCallingIdentity(origId);
1650 }
1651 }
1652 }
1653
1654 @Override
1655 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1656 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001657 try {
1658 WindowProcessController proc = null;
1659 synchronized (mGlobalLock) {
1660 ActivityStack stack = ActivityRecord.getStackLocked(token);
1661 if (stack == null) {
1662 return;
1663 }
1664 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1665 false /* fromTimeout */, false /* processPausingActivities */, config);
1666 if (r != null) {
1667 proc = r.app;
1668 }
1669 if (stopProfiling && proc != null) {
1670 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001671 }
1672 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001673 } finally {
1674 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677
1678 @Override
1679 public final void activityResumed(IBinder token) {
1680 final long origId = Binder.clearCallingIdentity();
1681 synchronized (mGlobalLock) {
1682 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001683 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685 Binder.restoreCallingIdentity(origId);
1686 }
1687
1688 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001689 public final void activityTopResumedStateLost() {
1690 final long origId = Binder.clearCallingIdentity();
1691 synchronized (mGlobalLock) {
1692 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1693 }
1694 Binder.restoreCallingIdentity(origId);
1695 }
1696
1697 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 public final void activityPaused(IBinder token) {
1699 final long origId = Binder.clearCallingIdentity();
1700 synchronized (mGlobalLock) {
1701 ActivityStack stack = ActivityRecord.getStackLocked(token);
1702 if (stack != null) {
1703 stack.activityPausedLocked(token, false);
1704 }
1705 }
1706 Binder.restoreCallingIdentity(origId);
1707 }
1708
1709 @Override
1710 public final void activityStopped(IBinder token, Bundle icicle,
1711 PersistableBundle persistentState, CharSequence description) {
1712 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1713
1714 // Refuse possible leaked file descriptors
1715 if (icicle != null && icicle.hasFileDescriptors()) {
1716 throw new IllegalArgumentException("File descriptors passed in Bundle");
1717 }
1718
1719 final long origId = Binder.clearCallingIdentity();
1720
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001721 String restartingName = null;
1722 int restartingUid = 0;
1723 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001724 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001725 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001727 if (r.attachedToProcess()
1728 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1729 // The activity was requested to restart from
1730 // {@link #restartActivityProcessIfVisible}.
1731 restartingName = r.app.mName;
1732 restartingUid = r.app.mUid;
1733 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001734 r.activityStoppedLocked(icicle, persistentState, description);
1735 }
1736 }
1737
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001738 if (restartingName != null) {
1739 // In order to let the foreground activity can be restarted with its saved state from
1740 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1741 // until the activity reports stopped with the state. And the activity record will be
1742 // kept because the record state is restarting, then the activity will be restarted
1743 // immediately if it is still the top one.
1744 mStackSupervisor.removeRestartTimeouts(r);
1745 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1746 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001747 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748
1749 Binder.restoreCallingIdentity(origId);
1750 }
1751
1752 @Override
1753 public final void activityDestroyed(IBinder token) {
1754 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1755 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001756 final long origId = Binder.clearCallingIdentity();
1757 try {
1758 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1759 if (activity != null) {
1760 activity.destroyed("activityDestroyed");
1761 }
1762 } finally {
1763 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 }
1765 }
1766 }
1767
1768 @Override
1769 public final void activityRelaunched(IBinder token) {
1770 final long origId = Binder.clearCallingIdentity();
1771 synchronized (mGlobalLock) {
1772 mStackSupervisor.activityRelaunchedLocked(token);
1773 }
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776
1777 public final void activitySlept(IBinder token) {
1778 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1779
1780 final long origId = Binder.clearCallingIdentity();
1781
1782 synchronized (mGlobalLock) {
1783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1784 if (r != null) {
1785 mStackSupervisor.activitySleptLocked(r);
1786 }
1787 }
1788
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791
1792 @Override
1793 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1794 synchronized (mGlobalLock) {
1795 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1796 if (r == null) {
1797 return;
1798 }
1799 final long origId = Binder.clearCallingIdentity();
1800 try {
1801 r.setRequestedOrientation(requestedOrientation);
1802 } finally {
1803 Binder.restoreCallingIdentity(origId);
1804 }
1805 }
1806 }
1807
1808 @Override
1809 public int getRequestedOrientation(IBinder token) {
1810 synchronized (mGlobalLock) {
1811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1812 if (r == null) {
1813 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1814 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001815 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001816 }
1817 }
1818
1819 @Override
1820 public void setImmersive(IBinder token, boolean immersive) {
1821 synchronized (mGlobalLock) {
1822 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1823 if (r == null) {
1824 throw new IllegalArgumentException();
1825 }
1826 r.immersive = immersive;
1827
1828 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001829 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001831 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 }
1833 }
1834 }
1835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 void applyUpdateLockStateLocked(ActivityRecord r) {
1837 // Modifications to the UpdateLock state are done on our handler, outside
1838 // the activity manager's locks. The new state is determined based on the
1839 // state *now* of the relevant activity record. The object is passed to
1840 // the handler solely for logging detail, not to be consulted/modified.
1841 final boolean nextState = r != null && r.immersive;
1842 mH.post(() -> {
1843 if (mUpdateLock.isHeld() != nextState) {
1844 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1845 "Applying new update lock state '" + nextState + "' for " + r);
1846 if (nextState) {
1847 mUpdateLock.acquire();
1848 } else {
1849 mUpdateLock.release();
1850 }
1851 }
1852 });
1853 }
1854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 @Override
1856 public boolean isImmersive(IBinder token) {
1857 synchronized (mGlobalLock) {
1858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 throw new IllegalArgumentException();
1861 }
1862 return r.immersive;
1863 }
1864 }
1865
1866 @Override
1867 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001870 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 return (r != null) ? r.immersive : false;
1872 }
1873 }
1874
1875 @Override
1876 public void overridePendingTransition(IBinder token, String packageName,
1877 int enterAnim, int exitAnim) {
1878 synchronized (mGlobalLock) {
1879 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1880 if (self == null) {
1881 return;
1882 }
1883
1884 final long origId = Binder.clearCallingIdentity();
1885
1886 if (self.isState(
1887 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001888 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001889 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 }
1891
1892 Binder.restoreCallingIdentity(origId);
1893 }
1894 }
1895
1896 @Override
1897 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001900 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 if (r == null) {
1902 return ActivityManager.COMPAT_MODE_UNKNOWN;
1903 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001904 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 }
1906 }
1907
1908 @Override
1909 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001910 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001912 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001914 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 if (r == null) {
1916 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1917 return;
1918 }
1919 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001920 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 }
1922 }
1923
1924 @Override
1925 public int getLaunchedFromUid(IBinder activityToken) {
1926 ActivityRecord srec;
1927 synchronized (mGlobalLock) {
1928 srec = ActivityRecord.forTokenLocked(activityToken);
1929 }
1930 if (srec == null) {
1931 return -1;
1932 }
1933 return srec.launchedFromUid;
1934 }
1935
1936 @Override
1937 public String getLaunchedFromPackage(IBinder activityToken) {
1938 ActivityRecord srec;
1939 synchronized (mGlobalLock) {
1940 srec = ActivityRecord.forTokenLocked(activityToken);
1941 }
1942 if (srec == null) {
1943 return null;
1944 }
1945 return srec.launchedFromPackage;
1946 }
1947
1948 @Override
1949 public boolean convertFromTranslucent(IBinder token) {
1950 final long origId = Binder.clearCallingIdentity();
1951 try {
1952 synchronized (mGlobalLock) {
1953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1954 if (r == null) {
1955 return false;
1956 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001957 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 }
1959 } finally {
1960 Binder.restoreCallingIdentity(origId);
1961 }
1962 }
1963
1964 @Override
1965 public boolean convertToTranslucent(IBinder token, Bundle options) {
1966 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1967 final long origId = Binder.clearCallingIdentity();
1968 try {
1969 synchronized (mGlobalLock) {
1970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1971 if (r == null) {
1972 return false;
1973 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001974 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 int index = task.mActivities.lastIndexOf(r);
1976 if (index > 0) {
1977 ActivityRecord under = task.mActivities.get(index - 1);
1978 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1979 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001980 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001981 }
1982 } finally {
1983 Binder.restoreCallingIdentity(origId);
1984 }
1985 }
1986
1987 @Override
1988 public void notifyActivityDrawn(IBinder token) {
1989 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1990 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001991 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001993 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 }
1995 }
1996 }
1997
1998 @Override
1999 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2000 synchronized (mGlobalLock) {
2001 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2002 if (r == null) {
2003 return;
2004 }
2005 r.reportFullyDrawnLocked(restoredFromBundle);
2006 }
2007 }
2008
2009 @Override
2010 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2011 synchronized (mGlobalLock) {
2012 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2013 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2014 return stack.mDisplayId;
2015 }
2016 return DEFAULT_DISPLAY;
2017 }
2018 }
2019
2020 @Override
2021 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002023 long ident = Binder.clearCallingIdentity();
2024 try {
2025 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002026 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002028 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 }
2030 return null;
2031 }
2032 } finally {
2033 Binder.restoreCallingIdentity(ident);
2034 }
2035 }
2036
2037 @Override
2038 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002039 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2041 final long callingId = Binder.clearCallingIdentity();
2042 try {
2043 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002044 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002045 if (stack == null) {
2046 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2047 return;
2048 }
2049 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002050 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002051 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002052 }
2053 }
2054 } finally {
2055 Binder.restoreCallingIdentity(callingId);
2056 }
2057 }
2058
2059 @Override
2060 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002061 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002062 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2063 final long callingId = Binder.clearCallingIdentity();
2064 try {
2065 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002066 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002067 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 if (task == null) {
2069 return;
2070 }
2071 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002072 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002073 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002074 }
2075 }
2076 } finally {
2077 Binder.restoreCallingIdentity(callingId);
2078 }
2079 }
2080
2081 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002082 public void restartActivityProcessIfVisible(IBinder activityToken) {
2083 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2084 final long callingId = Binder.clearCallingIdentity();
2085 try {
2086 synchronized (mGlobalLock) {
2087 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2088 if (r == null) {
2089 return;
2090 }
2091 r.restartProcessIfVisible();
2092 }
2093 } finally {
2094 Binder.restoreCallingIdentity(callingId);
2095 }
2096 }
2097
2098 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002100 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 synchronized (mGlobalLock) {
2102 final long ident = Binder.clearCallingIdentity();
2103 try {
2104 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2105 "remove-task");
2106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
2109 }
2110 }
2111
2112 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002113 public void removeAllVisibleRecentTasks() {
2114 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2115 synchronized (mGlobalLock) {
2116 final long ident = Binder.clearCallingIdentity();
2117 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002118 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002119 } finally {
2120 Binder.restoreCallingIdentity(ident);
2121 }
2122 }
2123 }
2124
2125 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2127 synchronized (mGlobalLock) {
2128 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2129 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002130 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002131 }
2132 }
2133 return false;
2134 }
2135
2136 @Override
2137 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2138 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002139
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002140 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002141 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2142 if (r != null) {
2143 return r.getActivityStack().navigateUpToLocked(
2144 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002145 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002146 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002147 }
2148 }
2149
2150 /**
2151 * Attempts to move a task backwards in z-order (the order of activities within the task is
2152 * unchanged).
2153 *
2154 * There are several possible results of this call:
2155 * - if the task is locked, then we will show the lock toast
2156 * - if there is a task behind the provided task, then that task is made visible and resumed as
2157 * this task is moved to the back
2158 * - otherwise, if there are no other tasks in the stack:
2159 * - if this task is in the pinned stack, then we remove the stack completely, which will
2160 * have the effect of moving the task to the top or bottom of the fullscreen stack
2161 * (depending on whether it is visible)
2162 * - otherwise, we simply return home and hide this task
2163 *
2164 * @param token A reference to the activity we wish to move
2165 * @param nonRoot If false then this only works if the activity is the root
2166 * of a task; if true it will work for any activity in a task.
2167 * @return Returns true if the move completed, false if not.
2168 */
2169 @Override
2170 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002171 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002172 synchronized (mGlobalLock) {
2173 final long origId = Binder.clearCallingIdentity();
2174 try {
2175 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002176 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 if (task != null) {
2178 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2179 }
2180 } finally {
2181 Binder.restoreCallingIdentity(origId);
2182 }
2183 }
2184 return false;
2185 }
2186
2187 @Override
2188 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002189 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002190 long ident = Binder.clearCallingIdentity();
2191 Rect rect = new Rect();
2192 try {
2193 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002194 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002195 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2196 if (task == null) {
2197 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2198 return rect;
2199 }
2200 if (task.getStack() != null) {
2201 // Return the bounds from window manager since it will be adjusted for various
2202 // things like the presense of a docked stack for tasks that aren't resizeable.
2203 task.getWindowContainerBounds(rect);
2204 } else {
2205 // Task isn't in window manager yet since it isn't associated with a stack.
2206 // Return the persist value from activity manager
2207 if (!task.matchParentBounds()) {
2208 rect.set(task.getBounds());
2209 } else if (task.mLastNonFullscreenBounds != null) {
2210 rect.set(task.mLastNonFullscreenBounds);
2211 }
2212 }
2213 }
2214 } finally {
2215 Binder.restoreCallingIdentity(ident);
2216 }
2217 return rect;
2218 }
2219
2220 @Override
2221 public ActivityManager.TaskDescription getTaskDescription(int id) {
2222 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002223 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002225 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2227 if (tr != null) {
2228 return tr.lastTaskDescription;
2229 }
2230 }
2231 return null;
2232 }
2233
2234 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002235 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2236 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2237 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2238 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2239 return;
2240 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002241 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002242 synchronized (mGlobalLock) {
2243 final long ident = Binder.clearCallingIdentity();
2244 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002245 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002246 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002247 if (task == null) {
2248 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2249 return;
2250 }
2251
2252 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2253 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2254
2255 if (!task.isActivityTypeStandardOrUndefined()) {
2256 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2257 + " non-standard task " + taskId + " to windowing mode="
2258 + windowingMode);
2259 }
2260
2261 final ActivityStack stack = task.getStack();
2262 if (toTop) {
2263 stack.moveToFront("setTaskWindowingMode", task);
2264 }
2265 stack.setWindowingMode(windowingMode);
2266 } finally {
2267 Binder.restoreCallingIdentity(ident);
2268 }
2269 }
2270 }
2271
2272 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002274 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 ActivityRecord r = getCallingRecordLocked(token);
2276 return r != null ? r.info.packageName : null;
2277 }
2278 }
2279
2280 @Override
2281 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002282 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002283 ActivityRecord r = getCallingRecordLocked(token);
2284 return r != null ? r.intent.getComponent() : null;
2285 }
2286 }
2287
2288 private ActivityRecord getCallingRecordLocked(IBinder token) {
2289 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2290 if (r == null) {
2291 return null;
2292 }
2293 return r.resultTo;
2294 }
2295
2296 @Override
2297 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002298 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002299
2300 synchronized (mGlobalLock) {
2301 final long origId = Binder.clearCallingIdentity();
2302 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002303 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002304 } finally {
2305 Binder.restoreCallingIdentity(origId);
2306 }
2307 }
2308 }
2309
Mark Renouf446251d2019-04-26 10:22:41 -04002310 @Override
2311 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2312 synchronized (mGlobalLock) {
2313 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2314 if (r == null) {
2315 return;
2316 }
2317 ActivityStack stack = r.getActivityStack();
2318 if (stack != null && stack.isSingleTaskInstance()) {
2319 // Single-task stacks are used for activities which are presented in floating
2320 // windows above full screen activities. Instead of directly finishing the
2321 // task, a task change listener is used to notify SystemUI so the action can be
2322 // handled specially.
2323 final TaskRecord task = r.getTaskRecord();
2324 mTaskChangeNotificationController
2325 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2326 } else {
2327 try {
2328 callback.requestFinish();
2329 } catch (RemoteException e) {
2330 Slog.e(TAG, "Failed to invoke request finish callback", e);
2331 }
2332 }
2333 }
2334 }
2335
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002336 /**
2337 * TODO: Add mController hook
2338 */
2339 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002340 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2341 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002342 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002343
2344 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2345 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002346 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2347 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348 }
2349 }
2350
Ricky Waiaca8a772019-04-04 16:01:06 +01002351 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2352 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002353 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002354
Ricky Waiaca8a772019-04-04 16:01:06 +01002355 final int callingPid = Binder.getCallingPid();
2356 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002357 if (!isSameApp(callingUid, callingPackage)) {
2358 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2359 + Binder.getCallingPid() + " as package " + callingPackage;
2360 Slog.w(TAG, msg);
2361 throw new SecurityException(msg);
2362 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002363 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 SafeActivityOptions.abort(options);
2365 return;
2366 }
2367 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 WindowProcessController callerApp = null;
2369 if (appThread != null) {
2370 callerApp = getProcessController(appThread);
2371 }
2372 final ActivityStarter starter = getActivityStartController().obtainStarter(
2373 null /* intent */, "moveTaskToFront");
2374 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2375 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002376 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002377 return;
2378 }
2379 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002381 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 if (task == null) {
2383 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002384 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002385 return;
2386 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002387 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002389 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 return;
2391 }
2392 ActivityOptions realOptions = options != null
2393 ? options.getOptions(mStackSupervisor)
2394 : null;
2395 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2396 false /* forceNonResizable */);
2397
2398 final ActivityRecord topActivity = task.getTopActivity();
2399 if (topActivity != null) {
2400
2401 // We are reshowing a task, use a starting window to hide the initial draw delay
2402 // so the transition can start earlier.
2403 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2404 true /* taskSwitch */, fromRecents);
2405 }
2406 } finally {
2407 Binder.restoreCallingIdentity(origId);
2408 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002409 }
2410
Ricky Waiaca8a772019-04-04 16:01:06 +01002411 /**
2412 * Return true if callingUid is system, or packageName belongs to that callingUid.
2413 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002414 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002415 try {
2416 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2417 if (packageName == null) {
2418 return false;
2419 }
2420 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2421 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2422 UserHandle.getUserId(callingUid));
2423 return UserHandle.isSameApp(callingUid, uid);
2424 }
2425 } catch (RemoteException e) {
2426 // Should not happen
2427 }
2428 return true;
2429 }
2430
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002431 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2432 int callingPid, int callingUid, String name) {
2433 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2434 return true;
2435 }
2436
2437 if (getRecentTasks().isCallerRecents(sourceUid)) {
2438 return true;
2439 }
2440
2441 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2442 if (perm == PackageManager.PERMISSION_GRANTED) {
2443 return true;
2444 }
2445 if (checkAllowAppSwitchUid(sourceUid)) {
2446 return true;
2447 }
2448
2449 // If the actual IPC caller is different from the logical source, then
2450 // also see if they are allowed to control app switches.
2451 if (callingUid != -1 && callingUid != sourceUid) {
2452 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2453 if (perm == PackageManager.PERMISSION_GRANTED) {
2454 return true;
2455 }
2456 if (checkAllowAppSwitchUid(callingUid)) {
2457 return true;
2458 }
2459 }
2460
2461 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2462 return false;
2463 }
2464
2465 private boolean checkAllowAppSwitchUid(int uid) {
2466 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2467 if (types != null) {
2468 for (int i = types.size() - 1; i >= 0; i--) {
2469 if (types.valueAt(i).intValue() == uid) {
2470 return true;
2471 }
2472 }
2473 }
2474 return false;
2475 }
2476
2477 @Override
2478 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2479 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2480 "setActivityController()");
2481 synchronized (mGlobalLock) {
2482 mController = controller;
2483 mControllerIsAMonkey = imAMonkey;
2484 Watchdog.getInstance().setActivityController(controller);
2485 }
2486 }
2487
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002488 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002489 synchronized (mGlobalLock) {
2490 return mController != null && mControllerIsAMonkey;
2491 }
2492 }
2493
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002494 @Override
2495 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2496 synchronized (mGlobalLock) {
2497 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2498 }
2499 }
2500
2501 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2503 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2504 }
2505
2506 @Override
2507 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2508 @WindowConfiguration.ActivityType int ignoreActivityType,
2509 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2510 final int callingUid = Binder.getCallingUid();
2511 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2512
2513 synchronized (mGlobalLock) {
2514 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002516 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002518 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002519 ignoreWindowingMode, callingUid, allowed);
2520 }
2521
2522 return list;
2523 }
2524
2525 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002526 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2527 synchronized (mGlobalLock) {
2528 final long origId = Binder.clearCallingIdentity();
2529 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2530 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002531 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002532 }
2533 Binder.restoreCallingIdentity(origId);
2534 }
2535 }
2536
2537 @Override
2538 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002539 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002540 ActivityStack stack = ActivityRecord.getStackLocked(token);
2541 if (stack != null) {
2542 return stack.willActivityBeVisibleLocked(token);
2543 }
2544 return false;
2545 }
2546 }
2547
2548 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002550 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 synchronized (mGlobalLock) {
2552 final long ident = Binder.clearCallingIdentity();
2553 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002554 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002555 if (task == null) {
2556 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2557 return;
2558 }
2559
2560 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2561 + " to stackId=" + stackId + " toTop=" + toTop);
2562
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 if (stack == null) {
2565 throw new IllegalStateException(
2566 "moveTaskToStack: No stack for stackId=" + stackId);
2567 }
2568 if (!stack.isActivityTypeStandardOrUndefined()) {
2569 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2570 + taskId + " to stack " + stackId);
2571 }
2572 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002573 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002574 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2575 }
2576 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2577 "moveTaskToStack");
2578 } finally {
2579 Binder.restoreCallingIdentity(ident);
2580 }
2581 }
2582 }
2583
2584 @Override
2585 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2586 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002587 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002588
2589 final long ident = Binder.clearCallingIdentity();
2590 try {
2591 synchronized (mGlobalLock) {
2592 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002593 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002594 if (stack == null) {
2595 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2596 return;
2597 }
2598 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2599 throw new IllegalArgumentException("Stack: " + stackId
2600 + " doesn't support animated resize.");
2601 }
2602 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2603 animationDuration, false /* fromFullscreen */);
2604 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002605 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002606 if (stack == null) {
2607 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2608 return;
2609 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002610 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2612 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2613 }
2614 }
2615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
2618 }
2619
wilsonshih5c4cf522019-01-25 09:03:47 +08002620 @Override
2621 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2622 int animationDuration) {
2623 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2624
2625 final long ident = Binder.clearCallingIdentity();
2626 try {
2627 synchronized (mGlobalLock) {
2628 if (xOffset == 0 && yOffset == 0) {
2629 return;
2630 }
2631 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2632 if (stack == null) {
2633 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2634 return;
2635 }
2636 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2637 throw new IllegalArgumentException("Stack: " + stackId
2638 + " doesn't support animated resize.");
2639 }
2640 final Rect destBounds = new Rect();
2641 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002642 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002643 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2644 return;
2645 }
2646 destBounds.offset(xOffset, yOffset);
2647 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2648 animationDuration, false /* fromFullscreen */);
2649 }
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
2653 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002654 /**
2655 * Moves the specified task to the primary-split-screen stack.
2656 *
2657 * @param taskId Id of task to move.
2658 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2659 * exist already. See
2660 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2661 * and
2662 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2663 * @param toTop If the task and stack should be moved to the top.
2664 * @param animate Whether we should play an animation for the moving the task.
2665 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2666 * stack. Pass {@code null} to use default bounds.
2667 * @param showRecents If the recents activity should be shown on the other side of the task
2668 * going into split-screen mode.
2669 */
2670 @Override
2671 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2672 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002673 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002674 "setTaskWindowingModeSplitScreenPrimary()");
2675 synchronized (mGlobalLock) {
2676 final long ident = Binder.clearCallingIdentity();
2677 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002678 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002679 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002680 if (task == null) {
2681 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2682 return false;
2683 }
2684 if (DEBUG_STACK) Slog.d(TAG_STACK,
2685 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2686 + " to createMode=" + createMode + " toTop=" + toTop);
2687 if (!task.isActivityTypeStandardOrUndefined()) {
2688 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2689 + " non-standard task " + taskId + " to split-screen windowing mode");
2690 }
2691
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002692 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002693 final int windowingMode = task.getWindowingMode();
2694 final ActivityStack stack = task.getStack();
2695 if (toTop) {
2696 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2697 }
2698 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002699 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2700 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002701 return windowingMode != task.getWindowingMode();
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706 }
2707
2708 /**
2709 * Removes stacks in the input windowing modes from the system if they are of activity type
2710 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2711 */
2712 @Override
2713 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 "removeStacksInWindowingModes()");
2716
2717 synchronized (mGlobalLock) {
2718 final long ident = Binder.clearCallingIdentity();
2719 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002720 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 } finally {
2722 Binder.restoreCallingIdentity(ident);
2723 }
2724 }
2725 }
2726
2727 @Override
2728 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002729 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002730 "removeStacksWithActivityTypes()");
2731
2732 synchronized (mGlobalLock) {
2733 final long ident = Binder.clearCallingIdentity();
2734 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002735 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002736 } finally {
2737 Binder.restoreCallingIdentity(ident);
2738 }
2739 }
2740 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002741
2742 @Override
2743 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2744 int userId) {
2745 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002746 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2747 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002748 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002749 final boolean detailed = checkGetTasksPermission(
2750 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2751 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 == PackageManager.PERMISSION_GRANTED;
2753
2754 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002755 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 callingUid);
2757 }
2758 }
2759
2760 @Override
2761 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002762 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 long ident = Binder.clearCallingIdentity();
2764 try {
2765 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002766 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 } finally {
2769 Binder.restoreCallingIdentity(ident);
2770 }
2771 }
2772
2773 @Override
2774 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002775 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 long ident = Binder.clearCallingIdentity();
2777 try {
2778 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002779 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 }
2781 } finally {
2782 Binder.restoreCallingIdentity(ident);
2783 }
2784 }
2785
2786 @Override
2787 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 final long callingUid = Binder.getCallingUid();
2790 final long origId = Binder.clearCallingIdentity();
2791 try {
2792 synchronized (mGlobalLock) {
2793 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002794 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2796 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(origId);
2800 }
2801 }
2802
2803 @Override
2804 public void startLockTaskModeByToken(IBinder token) {
2805 synchronized (mGlobalLock) {
2806 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2807 if (r == null) {
2808 return;
2809 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002810 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 }
2812 }
2813
2814 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002815 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 // This makes inner call to look as if it was initiated by system.
2818 long ident = Binder.clearCallingIdentity();
2819 try {
2820 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002821 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002822 MATCH_TASK_IN_STACKS_ONLY);
2823 if (task == null) {
2824 return;
2825 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002826
2827 // When starting lock task mode the stack must be in front and focused
2828 task.getStack().moveToFront("startSystemLockTaskMode");
2829 startLockTaskModeLocked(task, true /* isSystemCaller */);
2830 }
2831 } finally {
2832 Binder.restoreCallingIdentity(ident);
2833 }
2834 }
2835
2836 @Override
2837 public void stopLockTaskModeByToken(IBinder token) {
2838 synchronized (mGlobalLock) {
2839 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2840 if (r == null) {
2841 return;
2842 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002843 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002844 }
2845 }
2846
2847 /**
2848 * This API should be called by SystemUI only when user perform certain action to dismiss
2849 * lock task mode. We should only dismiss pinned lock task mode in this case.
2850 */
2851 @Override
2852 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002853 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002854 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2855 }
2856
2857 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2858 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2859 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2860 return;
2861 }
2862
Wale Ogunwaled32da472018-11-16 07:19:28 -08002863 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864 if (stack == null || task != stack.topTask()) {
2865 throw new IllegalArgumentException("Invalid task, not in foreground");
2866 }
2867
2868 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2869 // system or a specific app.
2870 // * System-initiated requests will only start the pinned mode (screen pinning)
2871 // * App-initiated requests
2872 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2873 // - will start the pinned mode, otherwise
2874 final int callingUid = Binder.getCallingUid();
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002878 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002880 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002881 } finally {
2882 Binder.restoreCallingIdentity(ident);
2883 }
2884 }
2885
2886 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2887 final int callingUid = Binder.getCallingUid();
2888 long ident = Binder.clearCallingIdentity();
2889 try {
2890 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002891 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 }
2893 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2894 // task and jumping straight into a call in the case of emergency call back.
2895 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2896 if (tm != null) {
2897 tm.showInCallScreen(false);
2898 }
2899 } finally {
2900 Binder.restoreCallingIdentity(ident);
2901 }
2902 }
2903
2904 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002905 public void updateLockTaskPackages(int userId, String[] packages) {
2906 final int callingUid = Binder.getCallingUid();
2907 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2908 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2909 "updateLockTaskPackages()");
2910 }
2911 synchronized (this) {
2912 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2913 + Arrays.toString(packages));
2914 getLockTaskController().updateLockTaskPackages(userId, packages);
2915 }
2916 }
2917
2918 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002919 public boolean isInLockTaskMode() {
2920 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2921 }
2922
2923 @Override
2924 public int getLockTaskModeState() {
2925 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002926 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 }
2928 }
2929
2930 @Override
2931 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2932 synchronized (mGlobalLock) {
2933 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2934 if (r != null) {
2935 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002936 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002938 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 }
2940 }
2941 }
2942
2943 @Override
2944 public Bundle getActivityOptions(IBinder token) {
2945 final long origId = Binder.clearCallingIdentity();
2946 try {
2947 synchronized (mGlobalLock) {
2948 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2949 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002950 final ActivityOptions activityOptions = r.takeOptionsLocked(
2951 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 return activityOptions == null ? null : activityOptions.toBundle();
2953 }
2954 return null;
2955 }
2956 } finally {
2957 Binder.restoreCallingIdentity(origId);
2958 }
2959 }
2960
2961 @Override
2962 public List<IBinder> getAppTasks(String callingPackage) {
2963 int callingUid = Binder.getCallingUid();
2964 long ident = Binder.clearCallingIdentity();
2965 try {
2966 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002967 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 }
2969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
2972 }
2973
2974 @Override
2975 public void finishVoiceTask(IVoiceInteractionSession session) {
2976 synchronized (mGlobalLock) {
2977 final long origId = Binder.clearCallingIdentity();
2978 try {
2979 // TODO: VI Consider treating local voice interactions and voice tasks
2980 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002981 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 } finally {
2983 Binder.restoreCallingIdentity(origId);
2984 }
2985 }
2986
2987 }
2988
2989 @Override
2990 public boolean isTopOfTask(IBinder token) {
2991 synchronized (mGlobalLock) {
2992 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002993 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002994 }
2995 }
2996
2997 @Override
2998 public void notifyLaunchTaskBehindComplete(IBinder token) {
2999 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3000 }
3001
3002 @Override
3003 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003004 mH.post(() -> {
3005 synchronized (mGlobalLock) {
3006 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003007 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003009 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003010 } catch (RemoteException e) {
3011 }
3012 }
3013 }
3014
3015 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 }
3017
3018 /** Called from an app when assist data is ready. */
3019 @Override
3020 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3021 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003022 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003023 synchronized (pae) {
3024 pae.result = extras;
3025 pae.structure = structure;
3026 pae.content = content;
3027 if (referrer != null) {
3028 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3029 }
3030 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003031 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003032 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3033 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 structure.setHomeActivity(pae.isHome);
3035 }
3036 pae.haveResult = true;
3037 pae.notifyAll();
3038 if (pae.intent == null && pae.receiver == null) {
3039 // Caller is just waiting for the result.
3040 return;
3041 }
3042 }
3043 // We are now ready to launch the assist activity.
3044 IAssistDataReceiver sendReceiver = null;
3045 Bundle sendBundle = null;
3046 synchronized (mGlobalLock) {
3047 buildAssistBundleLocked(pae, extras);
3048 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003049 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003050 if (!exists) {
3051 // Timed out.
3052 return;
3053 }
3054
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 // Caller wants result sent back to them.
3057 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003058 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3059 pae.activity.getTaskRecord().taskId);
3060 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3061 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003062 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3063 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3064 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3065 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3066 }
3067 }
3068 if (sendReceiver != null) {
3069 try {
3070 sendReceiver.onHandleAssistData(sendBundle);
3071 } catch (RemoteException e) {
3072 }
3073 return;
3074 }
3075
3076 final long ident = Binder.clearCallingIdentity();
3077 try {
3078 if (TextUtils.equals(pae.intent.getAction(),
3079 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003080 // Start voice interaction through VoiceInteractionManagerService.
3081 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3082 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003083 } else {
3084 pae.intent.replaceExtras(pae.extras);
3085 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3086 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3087 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003088 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089
3090 try {
3091 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3092 } catch (ActivityNotFoundException e) {
3093 Slog.w(TAG, "No activity to handle assist action.", e);
3094 }
3095 }
3096 } finally {
3097 Binder.restoreCallingIdentity(ident);
3098 }
3099 }
3100
3101 @Override
3102 public int addAppTask(IBinder activityToken, Intent intent,
3103 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3104 final int callingUid = Binder.getCallingUid();
3105 final long callingIdent = Binder.clearCallingIdentity();
3106
3107 try {
3108 synchronized (mGlobalLock) {
3109 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3110 if (r == null) {
3111 throw new IllegalArgumentException("Activity does not exist; token="
3112 + activityToken);
3113 }
3114 ComponentName comp = intent.getComponent();
3115 if (comp == null) {
3116 throw new IllegalArgumentException("Intent " + intent
3117 + " must specify explicit component");
3118 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003119 if (thumbnail.getWidth() != mThumbnailWidth
3120 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003121 throw new IllegalArgumentException("Bad thumbnail size: got "
3122 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003123 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003124 }
3125 if (intent.getSelector() != null) {
3126 intent.setSelector(null);
3127 }
3128 if (intent.getSourceBounds() != null) {
3129 intent.setSourceBounds(null);
3130 }
3131 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3132 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3133 // The caller has added this as an auto-remove task... that makes no
3134 // sense, so turn off auto-remove.
3135 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3136 }
3137 }
3138 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3139 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3140 if (ainfo.applicationInfo.uid != callingUid) {
3141 throw new SecurityException(
3142 "Can't add task for another application: target uid="
3143 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3144 }
3145
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003146 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003148 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003150 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 // The app has too many tasks already and we can't add any more
3152 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3153 return INVALID_TASK_ID;
3154 }
3155 task.lastTaskDescription.copyFrom(description);
3156
3157 // TODO: Send the thumbnail to WM to store it.
3158
3159 return task.taskId;
3160 }
3161 } finally {
3162 Binder.restoreCallingIdentity(callingIdent);
3163 }
3164 }
3165
3166 @Override
3167 public Point getAppTaskThumbnailSize() {
3168 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003169 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 }
3171 }
3172
3173 @Override
3174 public void setTaskResizeable(int taskId, int resizeableMode) {
3175 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003176 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003177 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3178 if (task == null) {
3179 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3180 return;
3181 }
3182 task.setResizeMode(resizeableMode);
3183 }
3184 }
3185
3186 @Override
3187 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003188 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 long ident = Binder.clearCallingIdentity();
3190 try {
3191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003192 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003193 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 if (task == null) {
3195 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3196 return;
3197 }
3198 // Place the task in the right stack if it isn't there already based on
3199 // the requested bounds.
3200 // The stack transition logic is:
3201 // - a null bounds on a freeform task moves that task to fullscreen
3202 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3203 // that task to freeform
3204 // - otherwise the task is not moved
3205 ActivityStack stack = task.getStack();
3206 if (!task.getWindowConfiguration().canResizeTask()) {
3207 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3208 }
3209 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3210 stack = stack.getDisplay().getOrCreateStack(
3211 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3212 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3213 stack = stack.getDisplay().getOrCreateStack(
3214 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3215 }
3216
3217 // Reparent the task to the right stack if necessary
3218 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3219 if (stack != task.getStack()) {
3220 // Defer resume until the task is resized below
3221 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3222 DEFER_RESUME, "resizeTask");
3223 preserveWindow = false;
3224 }
3225
3226 // After reparenting (which only resizes the task to the stack bounds), resize the
3227 // task to the actual bounds provided
3228 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3229 }
3230 } finally {
3231 Binder.restoreCallingIdentity(ident);
3232 }
3233 }
3234
3235 @Override
3236 public boolean releaseActivityInstance(IBinder token) {
3237 synchronized (mGlobalLock) {
3238 final long origId = Binder.clearCallingIdentity();
3239 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003240 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3241 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 return false;
3243 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003244 r.destroyImmediately(true /* removeFromApp */, "app-req");
3245 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003246 } finally {
3247 Binder.restoreCallingIdentity(origId);
3248 }
3249 }
3250 }
3251
3252 @Override
3253 public void releaseSomeActivities(IApplicationThread appInt) {
3254 synchronized (mGlobalLock) {
3255 final long origId = Binder.clearCallingIdentity();
3256 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003257 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003258 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 } finally {
3260 Binder.restoreCallingIdentity(origId);
3261 }
3262 }
3263 }
3264
3265 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003266 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003267 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 != PackageManager.PERMISSION_GRANTED) {
3269 throw new SecurityException("Requires permission "
3270 + android.Manifest.permission.DEVICE_POWER);
3271 }
3272
3273 synchronized (mGlobalLock) {
3274 long ident = Binder.clearCallingIdentity();
3275 if (mKeyguardShown != keyguardShowing) {
3276 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003277 final Message msg = PooledLambda.obtainMessage(
3278 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3279 keyguardShowing);
3280 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 }
3282 try {
wilsonshih177261f2019-02-22 12:02:18 +08003283 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003284 } finally {
3285 Binder.restoreCallingIdentity(ident);
3286 }
3287 }
3288
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003289 mH.post(() -> {
3290 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3291 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3292 }
3293 });
3294 }
3295
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003296 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003297 mH.post(() -> {
3298 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3299 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3300 }
3301 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003302 }
3303
3304 @Override
3305 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003306 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3307 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308
3309 final File passedIconFile = new File(filePath);
3310 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3311 passedIconFile.getName());
3312 if (!legitIconFile.getPath().equals(filePath)
3313 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3314 throw new IllegalArgumentException("Bad file path: " + filePath
3315 + " passed for userId " + userId);
3316 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003317 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 }
3319
3320 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003321 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3323 final ActivityOptions activityOptions = safeOptions != null
3324 ? safeOptions.getOptions(mStackSupervisor)
3325 : null;
3326 if (activityOptions == null
3327 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3328 || activityOptions.getCustomInPlaceResId() == 0) {
3329 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3330 "with valid animation");
3331 }
lumark588a3e82018-07-20 18:53:54 +08003332 // Get top display of front most application.
3333 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3334 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003335 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3336 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3337 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003338 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003339 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003340 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 }
3342
3343 @Override
3344 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003345 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003346 synchronized (mGlobalLock) {
3347 final long ident = Binder.clearCallingIdentity();
3348 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003349 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 if (stack == null) {
3351 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3352 return;
3353 }
3354 if (!stack.isActivityTypeStandardOrUndefined()) {
3355 throw new IllegalArgumentException(
3356 "Removing non-standard stack is not allowed.");
3357 }
3358 mStackSupervisor.removeStack(stack);
3359 } finally {
3360 Binder.restoreCallingIdentity(ident);
3361 }
3362 }
3363 }
3364
3365 @Override
3366 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003367 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368
3369 synchronized (mGlobalLock) {
3370 final long ident = Binder.clearCallingIdentity();
3371 try {
3372 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3373 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003374 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003375 } finally {
3376 Binder.restoreCallingIdentity(ident);
3377 }
3378 }
3379 }
3380
3381 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003382 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 synchronized (mGlobalLock) {
3384 long ident = Binder.clearCallingIdentity();
3385 try {
3386 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3387 if (r == null) {
3388 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003389 "toggleFreeformWindowingMode: No activity record matching token="
3390 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003391 }
3392
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003393 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003394 if (stack == null) {
3395 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3396 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003397 }
3398
Yunfan Chend967af82019-01-17 18:30:18 +09003399 if (!stack.inFreeformWindowingMode()
3400 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3401 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3402 + "toggle between fullscreen and freeform.");
3403 }
3404
3405 if (stack.inFreeformWindowingMode()) {
3406 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003407 } else if (stack.getParent().inFreeformWindowingMode()) {
3408 // If the window is on a freeform display, set it to undefined. It will be
3409 // resolved to freeform and it can adjust windowing mode when the display mode
3410 // changes in runtime.
3411 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003412 } else {
3413 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3414 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003415 } finally {
3416 Binder.restoreCallingIdentity(ident);
3417 }
3418 }
3419 }
3420
3421 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3422 @Override
3423 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003426 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 }
3428
3429 /** Unregister a task stack listener so that it stops receiving callbacks. */
3430 @Override
3431 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003432 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003433 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003434 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 }
3436
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 @Override
3438 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3439 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3440 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3441 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3442 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3443 }
3444
3445 @Override
3446 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3447 IBinder activityToken, int flags) {
3448 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3449 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3450 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3451 }
3452
3453 @Override
3454 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3455 Bundle args) {
3456 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3457 true /* focused */, true /* newSessionId */, userHandle, args,
3458 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3459 }
3460
3461 @Override
3462 public Bundle getAssistContextExtras(int requestType) {
3463 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3464 null, null, true /* focused */, true /* newSessionId */,
3465 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3466 if (pae == null) {
3467 return null;
3468 }
3469 synchronized (pae) {
3470 while (!pae.haveResult) {
3471 try {
3472 pae.wait();
3473 } catch (InterruptedException e) {
3474 }
3475 }
3476 }
3477 synchronized (mGlobalLock) {
3478 buildAssistBundleLocked(pae, pae.result);
3479 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003480 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003481 }
3482 return pae.extras;
3483 }
3484
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003485 /**
3486 * Binder IPC calls go through the public entry point.
3487 * This can be called with or without the global lock held.
3488 */
3489 private static int checkCallingPermission(String permission) {
3490 return checkPermission(
3491 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3492 }
3493
3494 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003495 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003496 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3497 mAmInternal.enforceCallingPermission(permission, func);
3498 }
3499 }
3500
3501 @VisibleForTesting
3502 int checkGetTasksPermission(String permission, int pid, int uid) {
3503 return checkPermission(permission, pid, uid);
3504 }
3505
3506 static int checkPermission(String permission, int pid, int uid) {
3507 if (permission == null) {
3508 return PackageManager.PERMISSION_DENIED;
3509 }
3510 return checkComponentPermission(permission, pid, uid, -1, true);
3511 }
3512
Wale Ogunwale214f3482018-10-04 11:00:47 -07003513 public static int checkComponentPermission(String permission, int pid, int uid,
3514 int owningUid, boolean exported) {
3515 return ActivityManagerService.checkComponentPermission(
3516 permission, pid, uid, owningUid, exported);
3517 }
3518
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003519 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3520 if (getRecentTasks().isCallerRecents(callingUid)) {
3521 // Always allow the recents component to get tasks
3522 return true;
3523 }
3524
3525 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3526 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3527 if (!allowed) {
3528 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3529 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3530 // Temporary compatibility: some existing apps on the system image may
3531 // still be requesting the old permission and not switched to the new
3532 // one; if so, we'll still allow them full access. This means we need
3533 // to see if they are holding the old permission and are a system app.
3534 try {
3535 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3536 allowed = true;
3537 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3538 + " is using old GET_TASKS but privileged; allowing");
3539 }
3540 } catch (RemoteException e) {
3541 }
3542 }
3543 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3544 + " does not hold REAL_GET_TASKS; limiting output");
3545 }
3546 return allowed;
3547 }
3548
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003549 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3550 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3551 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3552 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003553 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 "enqueueAssistContext()");
3555
3556 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003557 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558 if (activity == null) {
3559 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3560 return null;
3561 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003562 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3564 return null;
3565 }
3566 if (focused) {
3567 if (activityToken != null) {
3568 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3569 if (activity != caller) {
3570 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3571 + " is not current top " + activity);
3572 return null;
3573 }
3574 }
3575 } else {
3576 activity = ActivityRecord.forTokenLocked(activityToken);
3577 if (activity == null) {
3578 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3579 + " couldn't be found");
3580 return null;
3581 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003582 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003583 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3584 return null;
3585 }
3586 }
3587
3588 PendingAssistExtras pae;
3589 Bundle extras = new Bundle();
3590 if (args != null) {
3591 extras.putAll(args);
3592 }
3593 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003594 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003595
3596 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3597 userHandle);
3598 pae.isHome = activity.isActivityTypeHome();
3599
3600 // Increment the sessionId if necessary
3601 if (newSessionId) {
3602 mViSessionId++;
3603 }
3604 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003605 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3606 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003608 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 } catch (RemoteException e) {
3610 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3611 return null;
3612 }
3613 return pae;
3614 }
3615 }
3616
3617 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3618 if (result != null) {
3619 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3620 }
3621 if (pae.hint != null) {
3622 pae.extras.putBoolean(pae.hint, true);
3623 }
3624 }
3625
3626 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3627 IAssistDataReceiver receiver;
3628 synchronized (mGlobalLock) {
3629 mPendingAssistExtras.remove(pae);
3630 receiver = pae.receiver;
3631 }
3632 if (receiver != null) {
3633 // Caller wants result sent back to them.
3634 Bundle sendBundle = new Bundle();
3635 // At least return the receiver extras
3636 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3637 try {
3638 pae.receiver.onHandleAssistData(sendBundle);
3639 } catch (RemoteException e) {
3640 }
3641 }
3642 }
3643
3644 public class PendingAssistExtras extends Binder implements Runnable {
3645 public final ActivityRecord activity;
3646 public boolean isHome;
3647 public final Bundle extras;
3648 public final Intent intent;
3649 public final String hint;
3650 public final IAssistDataReceiver receiver;
3651 public final int userHandle;
3652 public boolean haveResult = false;
3653 public Bundle result = null;
3654 public AssistStructure structure = null;
3655 public AssistContent content = null;
3656 public Bundle receiverExtras;
3657
3658 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3659 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3660 int _userHandle) {
3661 activity = _activity;
3662 extras = _extras;
3663 intent = _intent;
3664 hint = _hint;
3665 receiver = _receiver;
3666 receiverExtras = _receiverExtras;
3667 userHandle = _userHandle;
3668 }
3669
3670 @Override
3671 public void run() {
3672 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3673 synchronized (this) {
3674 haveResult = true;
3675 notifyAll();
3676 }
3677 pendingAssistExtrasTimedOut(this);
3678 }
3679 }
3680
3681 @Override
3682 public boolean isAssistDataAllowedOnCurrentActivity() {
3683 int userId;
3684 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003685 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003686 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3687 return false;
3688 }
3689
3690 final ActivityRecord activity = focusedStack.getTopActivity();
3691 if (activity == null) {
3692 return false;
3693 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003694 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003695 }
3696 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3697 }
3698
3699 @Override
3700 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3701 long ident = Binder.clearCallingIdentity();
3702 try {
3703 synchronized (mGlobalLock) {
3704 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003705 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003706 if (top != caller) {
3707 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3708 + " is not current top " + top);
3709 return false;
3710 }
3711 if (!top.nowVisible) {
3712 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3713 + " is not visible");
3714 return false;
3715 }
3716 }
3717 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3718 token);
3719 } finally {
3720 Binder.restoreCallingIdentity(ident);
3721 }
3722 }
3723
3724 @Override
3725 public boolean isRootVoiceInteraction(IBinder token) {
3726 synchronized (mGlobalLock) {
3727 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3728 if (r == null) {
3729 return false;
3730 }
3731 return r.rootVoiceInteraction;
3732 }
3733 }
3734
Wale Ogunwalef6733932018-06-27 05:14:34 -07003735 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3736 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3737 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3738 if (activityToCallback == null) return;
3739 activityToCallback.setVoiceSessionLocked(voiceSession);
3740
3741 // Inform the activity
3742 try {
3743 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3744 voiceInteractor);
3745 long token = Binder.clearCallingIdentity();
3746 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003747 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003748 } finally {
3749 Binder.restoreCallingIdentity(token);
3750 }
3751 // TODO: VI Should we cache the activity so that it's easier to find later
3752 // rather than scan through all the stacks and activities?
3753 } catch (RemoteException re) {
3754 activityToCallback.clearVoiceSessionLocked();
3755 // TODO: VI Should this terminate the voice session?
3756 }
3757 }
3758
3759 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3760 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3761 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3762 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3763 boolean wasRunningVoice = mRunningVoice != null;
3764 mRunningVoice = session;
3765 if (!wasRunningVoice) {
3766 mVoiceWakeLock.acquire();
3767 updateSleepIfNeededLocked();
3768 }
3769 }
3770 }
3771
3772 void finishRunningVoiceLocked() {
3773 if (mRunningVoice != null) {
3774 mRunningVoice = null;
3775 mVoiceWakeLock.release();
3776 updateSleepIfNeededLocked();
3777 }
3778 }
3779
3780 @Override
3781 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3782 synchronized (mGlobalLock) {
3783 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3784 if (keepAwake) {
3785 mVoiceWakeLock.acquire();
3786 } else {
3787 mVoiceWakeLock.release();
3788 }
3789 }
3790 }
3791 }
3792
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 @Override
3794 public ComponentName getActivityClassForToken(IBinder token) {
3795 synchronized (mGlobalLock) {
3796 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3797 if (r == null) {
3798 return null;
3799 }
3800 return r.intent.getComponent();
3801 }
3802 }
3803
3804 @Override
3805 public String getPackageForToken(IBinder token) {
3806 synchronized (mGlobalLock) {
3807 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3808 if (r == null) {
3809 return null;
3810 }
3811 return r.packageName;
3812 }
3813 }
3814
3815 @Override
3816 public void showLockTaskEscapeMessage(IBinder token) {
3817 synchronized (mGlobalLock) {
3818 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3819 if (r == null) {
3820 return;
3821 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003822 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 }
3824 }
3825
3826 @Override
3827 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003828 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 final long token = Binder.clearCallingIdentity();
3830 try {
3831 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003832 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 }
3834 } finally {
3835 Binder.restoreCallingIdentity(token);
3836 }
3837 }
3838
3839 /**
3840 * Try to place task to provided position. The final position might be different depending on
3841 * current user and stacks state. The task will be moved to target stack if it's currently in
3842 * different stack.
3843 */
3844 @Override
3845 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003846 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 synchronized (mGlobalLock) {
3848 long ident = Binder.clearCallingIdentity();
3849 try {
3850 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3851 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003852 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003853 if (task == null) {
3854 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3855 + taskId);
3856 }
3857
Wale Ogunwaled32da472018-11-16 07:19:28 -08003858 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003859
3860 if (stack == null) {
3861 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3862 + stackId);
3863 }
3864 if (!stack.isActivityTypeStandardOrUndefined()) {
3865 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3866 + " the position of task " + taskId + " in/to non-standard stack");
3867 }
3868
3869 // TODO: Have the callers of this API call a separate reparent method if that is
3870 // what they intended to do vs. having this method also do reparenting.
3871 if (task.getStack() == stack) {
3872 // Change position in current stack.
3873 stack.positionChildAt(task, position);
3874 } else {
3875 // Reparent to new stack.
3876 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3877 !DEFER_RESUME, "positionTaskInStack");
3878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(ident);
3881 }
3882 }
3883 }
3884
3885 @Override
3886 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3887 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3888 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003889 + Arrays.toString(horizontalSizeConfiguration) + " "
3890 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 synchronized (mGlobalLock) {
3892 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3893 if (record == null) {
3894 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3895 + "found for: " + token);
3896 }
3897 record.setSizeConfigurations(horizontalSizeConfiguration,
3898 verticalSizeConfigurations, smallestSizeConfigurations);
3899 }
3900 }
3901
3902 /**
3903 * Dismisses split-screen multi-window mode.
3904 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3905 */
3906 @Override
3907 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003908 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003909 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3910 final long ident = Binder.clearCallingIdentity();
3911 try {
3912 synchronized (mGlobalLock) {
3913 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003914 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 if (stack == null) {
3916 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3917 return;
3918 }
3919
3920 if (toTop) {
3921 // Caller wants the current split-screen primary stack to be the top stack after
3922 // it goes fullscreen, so move it to the front.
3923 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003924 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003926 // stack after it goes fullscreen, so we move the focus to the top-most
3927 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3929 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3930 if (otherStack != null) {
3931 otherStack.moveToFront("dismissSplitScreenMode_other");
3932 }
3933 }
3934
Evan Rosky10475742018-09-05 19:02:48 -07003935 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936 }
3937 } finally {
3938 Binder.restoreCallingIdentity(ident);
3939 }
3940 }
3941
3942 /**
3943 * Dismisses Pip
3944 * @param animate True if the dismissal should be animated.
3945 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3946 * default animation duration should be used.
3947 */
3948 @Override
3949 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003950 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003951 final long ident = Binder.clearCallingIdentity();
3952 try {
3953 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003954 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003955 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 if (stack == null) {
3957 Slog.w(TAG, "dismissPip: pinned stack not found.");
3958 return;
3959 }
3960 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3961 throw new IllegalArgumentException("Stack: " + stack
3962 + " doesn't support animated resize.");
3963 }
3964 if (animate) {
3965 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3966 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3967 } else {
3968 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3969 }
3970 }
3971 } finally {
3972 Binder.restoreCallingIdentity(ident);
3973 }
3974 }
3975
3976 @Override
3977 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003978 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003979 synchronized (mGlobalLock) {
3980 mSuppressResizeConfigChanges = suppress;
3981 }
3982 }
3983
3984 /**
3985 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3986 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3987 * activity and clearing the task at the same time.
3988 */
3989 @Override
3990 // TODO: API should just be about changing windowing modes...
3991 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 "moveTasksToFullscreenStack()");
3994 synchronized (mGlobalLock) {
3995 final long origId = Binder.clearCallingIdentity();
3996 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003997 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 if (stack != null){
3999 if (!stack.isActivityTypeStandardOrUndefined()) {
4000 throw new IllegalArgumentException(
4001 "You can't move tasks from non-standard stacks.");
4002 }
4003 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4004 }
4005 } finally {
4006 Binder.restoreCallingIdentity(origId);
4007 }
4008 }
4009 }
4010
4011 /**
4012 * Moves the top activity in the input stackId to the pinned stack.
4013 *
4014 * @param stackId Id of stack to move the top activity to pinned stack.
4015 * @param bounds Bounds to use for pinned stack.
4016 *
4017 * @return True if the top activity of the input stack was successfully moved to the pinned
4018 * stack.
4019 */
4020 @Override
4021 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 "moveTopActivityToPinnedStack()");
4024 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004025 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004026 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4027 + "Device doesn't support picture-in-picture mode");
4028 }
4029
4030 long ident = Binder.clearCallingIdentity();
4031 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004032 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 } finally {
4034 Binder.restoreCallingIdentity(ident);
4035 }
4036 }
4037 }
4038
4039 @Override
4040 public boolean isInMultiWindowMode(IBinder token) {
4041 final long origId = Binder.clearCallingIdentity();
4042 try {
4043 synchronized (mGlobalLock) {
4044 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4045 if (r == null) {
4046 return false;
4047 }
4048 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4049 return r.inMultiWindowMode();
4050 }
4051 } finally {
4052 Binder.restoreCallingIdentity(origId);
4053 }
4054 }
4055
4056 @Override
4057 public boolean isInPictureInPictureMode(IBinder token) {
4058 final long origId = Binder.clearCallingIdentity();
4059 try {
4060 synchronized (mGlobalLock) {
4061 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4062 }
4063 } finally {
4064 Binder.restoreCallingIdentity(origId);
4065 }
4066 }
4067
4068 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004069 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4070 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 return false;
4072 }
4073
4074 // If we are animating to fullscreen then we have already dispatched the PIP mode
4075 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004076 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4077 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 }
4079
4080 @Override
4081 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4082 final long origId = Binder.clearCallingIdentity();
4083 try {
4084 synchronized (mGlobalLock) {
4085 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4086 "enterPictureInPictureMode", token, params);
4087
4088 // If the activity is already in picture in picture mode, then just return early
4089 if (isInPictureInPictureMode(r)) {
4090 return true;
4091 }
4092
4093 // Activity supports picture-in-picture, now check that we can enter PiP at this
4094 // point, if it is
4095 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4096 false /* beforeStopping */)) {
4097 return false;
4098 }
4099
4100 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004101 synchronized (mGlobalLock) {
4102 // Only update the saved args from the args that are set
4103 r.pictureInPictureArgs.copyOnlySet(params);
4104 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4105 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4106 // Adjust the source bounds by the insets for the transition down
4107 final Rect sourceBounds = new Rect(
4108 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004109 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004110 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004111 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004112 stack.setPictureInPictureAspectRatio(aspectRatio);
4113 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004114 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4115 r.info.applicationInfo.uid, r.shortComponentName,
4116 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004117 logPictureInPictureArgs(params);
4118 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 };
4120
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004121 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004122 // If the keyguard is showing or occluded, then try and dismiss it before
4123 // entering picture-in-picture (this will prompt the user to authenticate if the
4124 // device is currently locked).
4125 dismissKeyguard(token, new KeyguardDismissCallback() {
4126 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004127 public void onDismissSucceeded() {
4128 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 }
4130 }, null /* message */);
4131 } else {
4132 // Enter picture in picture immediately otherwise
4133 enterPipRunnable.run();
4134 }
4135 return true;
4136 }
4137 } finally {
4138 Binder.restoreCallingIdentity(origId);
4139 }
4140 }
4141
4142 @Override
4143 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4144 final long origId = Binder.clearCallingIdentity();
4145 try {
4146 synchronized (mGlobalLock) {
4147 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4148 "setPictureInPictureParams", token, params);
4149
4150 // Only update the saved args from the args that are set
4151 r.pictureInPictureArgs.copyOnlySet(params);
4152 if (r.inPinnedWindowingMode()) {
4153 // If the activity is already in picture-in-picture, update the pinned stack now
4154 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4155 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004156 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 if (!stack.isAnimatingBoundsToFullscreen()) {
4158 stack.setPictureInPictureAspectRatio(
4159 r.pictureInPictureArgs.getAspectRatio());
4160 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4161 }
4162 }
4163 logPictureInPictureArgs(params);
4164 }
4165 } finally {
4166 Binder.restoreCallingIdentity(origId);
4167 }
4168 }
4169
4170 @Override
4171 public int getMaxNumPictureInPictureActions(IBinder token) {
4172 // Currently, this is a static constant, but later, we may change this to be dependent on
4173 // the context of the activity
4174 return 3;
4175 }
4176
4177 private void logPictureInPictureArgs(PictureInPictureParams params) {
4178 if (params.hasSetActions()) {
4179 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4180 params.getActions().size());
4181 }
4182 if (params.hasSetAspectRatio()) {
4183 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4184 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4185 MetricsLogger.action(lm);
4186 }
4187 }
4188
4189 /**
4190 * Checks the state of the system and the activity associated with the given {@param token} to
4191 * verify that picture-in-picture is supported for that activity.
4192 *
4193 * @return the activity record for the given {@param token} if all the checks pass.
4194 */
4195 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4196 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004197 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198 throw new IllegalStateException(caller
4199 + ": Device doesn't support picture-in-picture mode.");
4200 }
4201
4202 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4203 if (r == null) {
4204 throw new IllegalStateException(caller
4205 + ": Can't find activity for token=" + token);
4206 }
4207
4208 if (!r.supportsPictureInPicture()) {
4209 throw new IllegalStateException(caller
4210 + ": Current activity does not support picture-in-picture.");
4211 }
4212
4213 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004214 && !mWindowManager.isValidPictureInPictureAspectRatio(
4215 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004216 final float minAspectRatio = mContext.getResources().getFloat(
4217 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4218 final float maxAspectRatio = mContext.getResources().getFloat(
4219 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4220 throw new IllegalArgumentException(String.format(caller
4221 + ": Aspect ratio is too extreme (must be between %f and %f).",
4222 minAspectRatio, maxAspectRatio));
4223 }
4224
4225 // Truncate the number of actions if necessary
4226 params.truncateActions(getMaxNumPictureInPictureActions(token));
4227
4228 return r;
4229 }
4230
4231 @Override
4232 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 synchronized (mGlobalLock) {
4235 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4236 if (r == null) {
4237 throw new IllegalArgumentException("Activity does not exist; token="
4238 + activityToken);
4239 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004240 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 }
4242 }
4243
4244 @Override
4245 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4246 Rect tempDockedTaskInsetBounds,
4247 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004248 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 long ident = Binder.clearCallingIdentity();
4250 try {
4251 synchronized (mGlobalLock) {
4252 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4253 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4254 PRESERVE_WINDOWS);
4255 }
4256 } finally {
4257 Binder.restoreCallingIdentity(ident);
4258 }
4259 }
4260
4261 @Override
4262 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004263 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004264 final long ident = Binder.clearCallingIdentity();
4265 try {
4266 synchronized (mGlobalLock) {
4267 mStackSupervisor.setSplitScreenResizing(resizing);
4268 }
4269 } finally {
4270 Binder.restoreCallingIdentity(ident);
4271 }
4272 }
4273
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004274 /**
4275 * Check that we have the features required for VR-related API calls, and throw an exception if
4276 * not.
4277 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004278 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004279 if (!mContext.getPackageManager().hasSystemFeature(
4280 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4281 throw new UnsupportedOperationException("VR mode not supported on this device!");
4282 }
4283 }
4284
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285 @Override
4286 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004287 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288
4289 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4290
4291 ActivityRecord r;
4292 synchronized (mGlobalLock) {
4293 r = ActivityRecord.isInStackLocked(token);
4294 }
4295
4296 if (r == null) {
4297 throw new IllegalArgumentException();
4298 }
4299
4300 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004301 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004302 VrManagerInternal.NO_ERROR) {
4303 return err;
4304 }
4305
4306 // Clear the binder calling uid since this path may call moveToTask().
4307 final long callingId = Binder.clearCallingIdentity();
4308 try {
4309 synchronized (mGlobalLock) {
4310 r.requestedVrComponent = (enabled) ? packageName : null;
4311
4312 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004313 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004314 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 }
4316 return 0;
4317 }
4318 } finally {
4319 Binder.restoreCallingIdentity(callingId);
4320 }
4321 }
4322
4323 @Override
4324 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4325 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4326 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004327 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4329 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4330 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004331 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 || activity.voiceSession != null) {
4333 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4334 return;
4335 }
4336 if (activity.pendingVoiceInteractionStart) {
4337 Slog.w(TAG, "Pending start of voice interaction already.");
4338 return;
4339 }
4340 activity.pendingVoiceInteractionStart = true;
4341 }
4342 LocalServices.getService(VoiceInteractionManagerInternal.class)
4343 .startLocalVoiceInteraction(callingActivity, options);
4344 }
4345
4346 @Override
4347 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4348 LocalServices.getService(VoiceInteractionManagerInternal.class)
4349 .stopLocalVoiceInteraction(callingActivity);
4350 }
4351
4352 @Override
4353 public boolean supportsLocalVoiceInteraction() {
4354 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4355 .supportsLocalVoiceInteraction();
4356 }
4357
4358 /** Notifies all listeners when the pinned stack animation starts. */
4359 @Override
4360 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363
4364 /** Notifies all listeners when the pinned stack animation ends. */
4365 @Override
4366 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004367 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 }
4369
4370 @Override
4371 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004372 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 final long ident = Binder.clearCallingIdentity();
4374 try {
4375 synchronized (mGlobalLock) {
4376 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4377 }
4378 } finally {
4379 Binder.restoreCallingIdentity(ident);
4380 }
4381 }
4382
4383 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004384 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004385 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004386
4387 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004390 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004391 }
4392
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004393 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004394 final Message msg = PooledLambda.obtainMessage(
4395 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4396 DEFAULT_DISPLAY);
4397 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399
4400 final long origId = Binder.clearCallingIdentity();
4401 try {
4402 if (values != null) {
4403 Settings.System.clearConfiguration(values);
4404 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004405 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 UserHandle.USER_NULL, false /* deferResume */,
4407 mTmpUpdateConfigurationResult);
4408 return mTmpUpdateConfigurationResult.changes != 0;
4409 } finally {
4410 Binder.restoreCallingIdentity(origId);
4411 }
4412 }
4413 }
4414
4415 @Override
4416 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4417 CharSequence message) {
4418 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004419 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4421 }
4422 final long callingId = Binder.clearCallingIdentity();
4423 try {
4424 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004425 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 }
4427 } finally {
4428 Binder.restoreCallingIdentity(callingId);
4429 }
4430 }
4431
4432 @Override
4433 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 "cancelTaskWindowTransition()");
4436 final long ident = Binder.clearCallingIdentity();
4437 try {
4438 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004439 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004440 MATCH_TASK_IN_STACKS_ONLY);
4441 if (task == null) {
4442 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4443 return;
4444 }
4445 task.cancelWindowTransition();
4446 }
4447 } finally {
4448 Binder.restoreCallingIdentity(ident);
4449 }
4450 }
4451
4452 @Override
4453 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004454 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 final long ident = Binder.clearCallingIdentity();
4456 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004457 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004458 } finally {
4459 Binder.restoreCallingIdentity(ident);
4460 }
4461 }
4462
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004463 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4464 boolean restoreFromDisk) {
4465 final TaskRecord task;
4466 synchronized (mGlobalLock) {
4467 task = mRootActivityContainer.anyTaskForId(taskId,
4468 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4469 if (task == null) {
4470 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4471 return null;
4472 }
4473 }
4474 // Don't call this while holding the lock as this operation might hit the disk.
4475 return task.getSnapshot(reducedResolution, restoreFromDisk);
4476 }
4477
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004478 @Override
4479 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4480 synchronized (mGlobalLock) {
4481 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4482 if (r == null) {
4483 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4484 + token);
4485 return;
4486 }
4487 final long origId = Binder.clearCallingIdentity();
4488 try {
4489 r.setDisablePreviewScreenshots(disable);
4490 } finally {
4491 Binder.restoreCallingIdentity(origId);
4492 }
4493 }
4494 }
4495
4496 /** Return the user id of the last resumed activity. */
4497 @Override
4498 public @UserIdInt
4499 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4502 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004503 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004504 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004506 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 }
4508 }
4509
4510 @Override
4511 public void updateLockTaskFeatures(int userId, int flags) {
4512 final int callingUid = Binder.getCallingUid();
4513 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 "updateLockTaskFeatures()");
4516 }
4517 synchronized (mGlobalLock) {
4518 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4519 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004520 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 }
4522 }
4523
4524 @Override
4525 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4526 synchronized (mGlobalLock) {
4527 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4528 if (r == null) {
4529 return;
4530 }
4531 final long origId = Binder.clearCallingIdentity();
4532 try {
4533 r.setShowWhenLocked(showWhenLocked);
4534 } finally {
4535 Binder.restoreCallingIdentity(origId);
4536 }
4537 }
4538 }
4539
4540 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004541 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4542 synchronized (mGlobalLock) {
4543 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4544 if (r == null) {
4545 return;
4546 }
4547 final long origId = Binder.clearCallingIdentity();
4548 try {
4549 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4550 } finally {
4551 Binder.restoreCallingIdentity(origId);
4552 }
4553 }
4554 }
4555
4556 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004557 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4558 synchronized (mGlobalLock) {
4559 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4560 if (r == null) {
4561 return;
4562 }
4563 final long origId = Binder.clearCallingIdentity();
4564 try {
4565 r.setTurnScreenOn(turnScreenOn);
4566 } finally {
4567 Binder.restoreCallingIdentity(origId);
4568 }
4569 }
4570 }
4571
4572 @Override
4573 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004574 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004575 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004576 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004577 synchronized (mGlobalLock) {
4578 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4579 if (r == null) {
4580 return;
4581 }
4582 final long origId = Binder.clearCallingIdentity();
4583 try {
4584 r.registerRemoteAnimations(definition);
4585 } finally {
4586 Binder.restoreCallingIdentity(origId);
4587 }
4588 }
4589 }
4590
4591 @Override
4592 public void registerRemoteAnimationForNextActivityStart(String packageName,
4593 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004594 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004595 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004596 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 synchronized (mGlobalLock) {
4598 final long origId = Binder.clearCallingIdentity();
4599 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004600 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004601 packageName, adapter);
4602 } finally {
4603 Binder.restoreCallingIdentity(origId);
4604 }
4605 }
4606 }
4607
Evan Rosky966759f2019-01-15 10:33:58 -08004608 @Override
4609 public void registerRemoteAnimationsForDisplay(int displayId,
4610 RemoteAnimationDefinition definition) {
4611 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4612 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004613 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004614 synchronized (mGlobalLock) {
4615 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4616 if (display == null) {
4617 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4618 return;
4619 }
4620 final long origId = Binder.clearCallingIdentity();
4621 try {
4622 display.mDisplayContent.registerRemoteAnimations(definition);
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627 }
4628
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004629 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4630 @Override
4631 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4632 synchronized (mGlobalLock) {
4633 final long origId = Binder.clearCallingIdentity();
4634 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004635 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004636 } finally {
4637 Binder.restoreCallingIdentity(origId);
4638 }
4639 }
4640 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004641
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004642 @Override
4643 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004644 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004645 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004646 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004647 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004648 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004649 }
4650 }
4651
4652 @Override
4653 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004655 != PERMISSION_GRANTED) {
4656 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4657 + Binder.getCallingPid()
4658 + ", uid=" + Binder.getCallingUid()
4659 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4660 Slog.w(TAG, msg);
4661 throw new SecurityException(msg);
4662 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004663 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004665 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004666 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004667 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004668 }
4669 }
4670
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004671 @Override
4672 public void stopAppSwitches() {
4673 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4674 synchronized (mGlobalLock) {
4675 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004676 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004677 mDidAppSwitch = false;
4678 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4679 }
4680 }
4681
4682 @Override
4683 public void resumeAppSwitches() {
4684 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4685 synchronized (mGlobalLock) {
4686 // Note that we don't execute any pending app switches... we will
4687 // let those wait until either the timeout, or the next start
4688 // activity request.
4689 mAppSwitchesAllowedTime = 0;
4690 }
4691 }
4692
Ricky Wai906af482019-06-03 17:25:28 +01004693 long getLastStopAppSwitchesTime() {
4694 return mLastStopAppSwitchesTime;
4695 }
4696
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004697 void onStartActivitySetDidAppSwitch() {
4698 if (mDidAppSwitch) {
4699 // This is the second allowed switch since we stopped switches, so now just generally
4700 // allow switches. Use case:
4701 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4702 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4703 // anyone to switch again).
4704 mAppSwitchesAllowedTime = 0;
4705 } else {
4706 mDidAppSwitch = true;
4707 }
4708 }
4709
4710 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004711 boolean shouldDisableNonVrUiLocked() {
4712 return mVrController.shouldDisableNonVrUiLocked();
4713 }
4714
Wale Ogunwale53783742018-09-16 10:21:51 -07004715 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004716 // 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 +00004717 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004719 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4720 + " to main display for VR");
4721 mRootActivityContainer.moveStackToDisplay(
4722 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 }
4724 mH.post(() -> {
4725 if (!mVrController.onVrModeChanged(r)) {
4726 return;
4727 }
4728 synchronized (mGlobalLock) {
4729 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4730 mWindowManager.disableNonVrUi(disableNonVrUi);
4731 if (disableNonVrUi) {
4732 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4733 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004734 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004735 }
4736 }
4737 });
4738 }
4739
Wale Ogunwale53783742018-09-16 10:21:51 -07004740 @Override
4741 public int getPackageScreenCompatMode(String packageName) {
4742 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4743 synchronized (mGlobalLock) {
4744 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4745 }
4746 }
4747
4748 @Override
4749 public void setPackageScreenCompatMode(String packageName, int mode) {
4750 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4751 "setPackageScreenCompatMode");
4752 synchronized (mGlobalLock) {
4753 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4754 }
4755 }
4756
4757 @Override
4758 public boolean getPackageAskScreenCompat(String packageName) {
4759 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4760 synchronized (mGlobalLock) {
4761 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4762 }
4763 }
4764
4765 @Override
4766 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4767 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4768 "setPackageAskScreenCompat");
4769 synchronized (mGlobalLock) {
4770 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4771 }
4772 }
4773
Wale Ogunwale64258362018-10-16 15:13:37 -07004774 public static String relaunchReasonToString(int relaunchReason) {
4775 switch (relaunchReason) {
4776 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4777 return "window_resize";
4778 case RELAUNCH_REASON_FREE_RESIZE:
4779 return "free_resize";
4780 default:
4781 return null;
4782 }
4783 }
4784
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004785 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004786 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004787 }
4788
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004789 /** Pokes the task persister. */
4790 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4791 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4792 }
4793
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004794 boolean isKeyguardLocked() {
4795 return mKeyguardController.isKeyguardLocked();
4796 }
4797
Garfield Tan01548632018-11-27 10:15:48 -08004798 /**
4799 * Clears launch params for the given package.
4800 * @param packageNames the names of the packages of which the launch params are to be cleared
4801 */
4802 @Override
4803 public void clearLaunchParamsForPackages(List<String> packageNames) {
4804 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4805 "clearLaunchParamsForPackages");
4806 synchronized (mGlobalLock) {
4807 for (int i = 0; i < packageNames.size(); ++i) {
4808 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4809 }
4810 }
4811 }
4812
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004813 /**
4814 * Makes the display with the given id a single task instance display. I.e the display can only
4815 * contain one task.
4816 */
4817 @Override
4818 public void setDisplayToSingleTaskInstance(int displayId) {
4819 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4820 "setDisplayToSingleTaskInstance");
4821 final long origId = Binder.clearCallingIdentity();
4822 try {
4823 final ActivityDisplay display =
4824 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4825 if (display != null) {
4826 display.setDisplayToSingleTaskInstance();
4827 }
4828 } finally {
4829 Binder.restoreCallingIdentity(origId);
4830 }
4831 }
4832
Wale Ogunwale31913b52018-10-13 08:29:31 -07004833 void dumpLastANRLocked(PrintWriter pw) {
4834 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4835 if (mLastANRState == null) {
4836 pw.println(" <no ANR has occurred since boot>");
4837 } else {
4838 pw.println(mLastANRState);
4839 }
4840 }
4841
4842 void dumpLastANRTracesLocked(PrintWriter pw) {
4843 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4844
4845 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4846 if (ArrayUtils.isEmpty(files)) {
4847 pw.println(" <no ANR has occurred since boot>");
4848 return;
4849 }
4850 // Find the latest file.
4851 File latest = null;
4852 for (File f : files) {
4853 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4854 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004855 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004856 }
4857 pw.print("File: ");
4858 pw.print(latest.getName());
4859 pw.println();
4860 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4861 String line;
4862 while ((line = in.readLine()) != null) {
4863 pw.println(line);
4864 }
4865 } catch (IOException e) {
4866 pw.print("Unable to read: ");
4867 pw.print(e);
4868 pw.println();
4869 }
4870 }
4871
4872 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4873 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4874 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4875 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4876 }
4877
4878 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4879 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4880 pw.println(header);
4881
Wale Ogunwaled32da472018-11-16 07:19:28 -08004882 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004883 dumpPackage);
4884 boolean needSep = printedAnything;
4885
4886 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004887 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004888 " ResumedActivity: ");
4889 if (printed) {
4890 printedAnything = true;
4891 needSep = false;
4892 }
4893
4894 if (dumpPackage == null) {
4895 if (needSep) {
4896 pw.println();
4897 }
4898 printedAnything = true;
4899 mStackSupervisor.dump(pw, " ");
4900 }
4901
4902 if (!printedAnything) {
4903 pw.println(" (nothing)");
4904 }
4905 }
4906
4907 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004908 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004909 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004910 pw.println(" ");
4911 }
4912
4913 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4914 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4915 getActivityStartController().dump(pw, "", dumpPackage);
4916 }
4917
4918 /**
4919 * There are three things that cmd can be:
4920 * - a flattened component name that matches an existing activity
4921 * - the cmd arg isn't the flattened component name of an existing activity:
4922 * dump all activity whose component contains the cmd as a substring
4923 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004924 * <p>
4925 * The caller should not hold lock when calling this method because it will wait for the
4926 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004927 *
4928 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4929 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4930 */
4931 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4932 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4933 ArrayList<ActivityRecord> activities;
4934
4935 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004936 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 dumpFocusedStackOnly);
4938 }
4939
4940 if (activities.size() <= 0) {
4941 return false;
4942 }
4943
4944 String[] newArgs = new String[args.length - opti];
4945 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4946
4947 TaskRecord lastTask = null;
4948 boolean needSep = false;
4949 for (int i = activities.size() - 1; i >= 0; i--) {
4950 ActivityRecord r = activities.get(i);
4951 if (needSep) {
4952 pw.println();
4953 }
4954 needSep = true;
4955 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004956 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004957 if (lastTask != task) {
4958 lastTask = task;
4959 pw.print("TASK "); pw.print(lastTask.affinity);
4960 pw.print(" id="); pw.print(lastTask.taskId);
4961 pw.print(" userId="); pw.println(lastTask.userId);
4962 if (dumpAll) {
4963 lastTask.dump(pw, " ");
4964 }
4965 }
4966 }
4967 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4968 }
4969 return true;
4970 }
4971
4972 /**
4973 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4974 * there is a thread associated with the activity.
4975 */
4976 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4977 final ActivityRecord r, String[] args, boolean dumpAll) {
4978 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004979 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004980 synchronized (mGlobalLock) {
4981 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4982 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4983 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004984 if (r.hasProcess()) {
4985 pw.println(r.app.getPid());
4986 appThread = r.app.getThread();
4987 } else {
4988 pw.println("(not running)");
4989 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 if (dumpAll) {
4991 r.dump(pw, innerPrefix);
4992 }
4993 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004994 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004995 // flush anything that is already in the PrintWriter since the thread is going
4996 // to write to the file descriptor directly
4997 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004998 try (TransferPipe tp = new TransferPipe()) {
4999 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5000 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005001 } catch (IOException e) {
5002 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5003 } catch (RemoteException e) {
5004 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5005 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005006 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005007 }
5008
sanryhuang498e77e2018-12-06 14:57:01 +08005009 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5010 boolean testPssMode) {
5011 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5012 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5013 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005014 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5016 st.toString());
5017 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005018 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5019 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5020 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005021 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5022 testPssMode);
5023 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005024 }
5025
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005026 int getCurrentUserId() {
5027 return mAmInternal.getCurrentUserId();
5028 }
5029
5030 private void enforceNotIsolatedCaller(String caller) {
5031 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5032 throw new SecurityException("Isolated process not allowed to call " + caller);
5033 }
5034 }
5035
Wale Ogunwalef6733932018-06-27 05:14:34 -07005036 public Configuration getConfiguration() {
5037 Configuration ci;
5038 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005039 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005040 ci.userSetLocale = false;
5041 }
5042 return ci;
5043 }
5044
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005045 /**
5046 * Current global configuration information. Contains general settings for the entire system,
5047 * also corresponds to the merged configuration of the default display.
5048 */
5049 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005050 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051 }
5052
5053 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5054 boolean initLocale) {
5055 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5056 }
5057
5058 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5059 boolean initLocale, boolean deferResume) {
5060 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5061 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5062 UserHandle.USER_NULL, deferResume);
5063 }
5064
Wale Ogunwale59507092018-10-29 09:00:30 -07005065 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005066 final long origId = Binder.clearCallingIdentity();
5067 try {
5068 synchronized (mGlobalLock) {
5069 updateConfigurationLocked(values, null, false, true, userId,
5070 false /* deferResume */);
5071 }
5072 } finally {
5073 Binder.restoreCallingIdentity(origId);
5074 }
5075 }
5076
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005077 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5078 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5079 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5080 deferResume, null /* result */);
5081 }
5082
5083 /**
5084 * Do either or both things: (1) change the current configuration, and (2)
5085 * make sure the given activity is running with the (now) current
5086 * configuration. Returns true if the activity has been left running, or
5087 * false if <var>starting</var> is being destroyed to match the new
5088 * configuration.
5089 *
5090 * @param userId is only used when persistent parameter is set to true to persist configuration
5091 * for that particular user
5092 */
5093 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5094 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5095 ActivityTaskManagerService.UpdateConfigurationResult result) {
5096 int changes = 0;
5097 boolean kept = true;
5098
5099 if (mWindowManager != null) {
5100 mWindowManager.deferSurfaceLayout();
5101 }
5102 try {
5103 if (values != null) {
5104 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5105 deferResume);
5106 }
5107
5108 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5109 } finally {
5110 if (mWindowManager != null) {
5111 mWindowManager.continueSurfaceLayout();
5112 }
5113 }
5114
5115 if (result != null) {
5116 result.changes = changes;
5117 result.activityRelaunched = !kept;
5118 }
5119 return kept;
5120 }
5121
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005122 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005123 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005125
5126 final ActivityDisplay defaultDisplay =
5127 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5128
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005129 mTempConfig.setTo(getGlobalConfiguration());
5130 final int changes = mTempConfig.updateFrom(values);
5131 if (changes == 0) {
5132 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5133 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5134 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5135 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005136 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 return 0;
5138 }
5139
5140 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5141 "Updating global configuration to: " + values);
5142
5143 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5144 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5145 values.colorMode,
5146 values.densityDpi,
5147 values.fontScale,
5148 values.hardKeyboardHidden,
5149 values.keyboard,
5150 values.keyboardHidden,
5151 values.mcc,
5152 values.mnc,
5153 values.navigation,
5154 values.navigationHidden,
5155 values.orientation,
5156 values.screenHeightDp,
5157 values.screenLayout,
5158 values.screenWidthDp,
5159 values.smallestScreenWidthDp,
5160 values.touchscreen,
5161 values.uiMode);
5162
5163
5164 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5165 final LocaleList locales = values.getLocales();
5166 int bestLocaleIndex = 0;
5167 if (locales.size() > 1) {
5168 if (mSupportedSystemLocales == null) {
5169 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5170 }
5171 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5172 }
5173 SystemProperties.set("persist.sys.locale",
5174 locales.get(bestLocaleIndex).toLanguageTag());
5175 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005176
5177 final Message m = PooledLambda.obtainMessage(
5178 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5179 locales.get(bestLocaleIndex));
5180 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005181 }
5182
Yunfan Chen75157d72018-07-27 14:47:21 +09005183 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005184
5185 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005186 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5189 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005190 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005191
5192 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005193 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194
5195 AttributeCache ac = AttributeCache.instance();
5196 if (ac != null) {
5197 ac.updateConfiguration(mTempConfig);
5198 }
5199
5200 // Make sure all resources in our process are updated right now, so that anyone who is going
5201 // to retrieve resource values after we return will be sure to get the new ones. This is
5202 // especially important during boot, where the first config change needs to guarantee all
5203 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005204 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205
5206 // We need another copy of global config because we're scheduling some calls instead of
5207 // running them in place. We need to be sure that object we send will be handled unchanged.
5208 final Configuration configCopy = new Configuration(mTempConfig);
5209 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005210 final Message msg = PooledLambda.obtainMessage(
5211 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5212 this, userId, configCopy);
5213 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005214 }
5215
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005216 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5217 for (int i = pidMap.size() - 1; i >= 0; i--) {
5218 final int pid = pidMap.keyAt(i);
5219 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005220 if (DEBUG_CONFIGURATION) {
5221 Slog.v(TAG_CONFIGURATION, "Update process config of "
5222 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005223 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005224 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
5226
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005227 final Message msg = PooledLambda.obtainMessage(
5228 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5229 mAmInternal, changes, initLocale);
5230 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231
5232 // Override configuration of the default display duplicates global config, so we need to
5233 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005234 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5235 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236
5237 return changes;
5238 }
5239
Wale Ogunwalef6733932018-06-27 05:14:34 -07005240 private void updateEventDispatchingLocked(boolean booted) {
5241 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5242 }
5243
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005244 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5245 final ContentResolver resolver = mContext.getContentResolver();
5246 Settings.System.putConfigurationForUser(resolver, config, userId);
5247 }
5248
5249 private void sendLocaleToMountDaemonMsg(Locale l) {
5250 try {
5251 IBinder service = ServiceManager.getService("mount");
5252 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5253 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5254 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5255 } catch (RemoteException e) {
5256 Log.e(TAG, "Error storing locale for decryption UI", e);
5257 }
5258 }
5259
Alison Cichowlas3e340502018-08-07 17:15:01 -04005260 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5261 mStartActivitySources.remove(permissionToken);
5262 mExpiredStartAsCallerTokens.add(permissionToken);
5263 }
5264
5265 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5266 mExpiredStartAsCallerTokens.remove(permissionToken);
5267 }
5268
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005269 boolean isActivityStartsLoggingEnabled() {
5270 return mAmInternal.isActivityStartsLoggingEnabled();
5271 }
5272
Michal Karpinski8596ded2018-11-14 14:43:48 +00005273 boolean isBackgroundActivityStartsEnabled() {
5274 return mAmInternal.isBackgroundActivityStartsEnabled();
5275 }
5276
Wale Ogunwalef6733932018-06-27 05:14:34 -07005277 void enableScreenAfterBoot(boolean booted) {
5278 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5279 SystemClock.uptimeMillis());
5280 mWindowManager.enableScreenAfterBoot();
5281
5282 synchronized (mGlobalLock) {
5283 updateEventDispatchingLocked(booted);
5284 }
5285 }
5286
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005287 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5288 if (r == null || !r.hasProcess()) {
5289 return KEY_DISPATCHING_TIMEOUT_MS;
5290 }
5291 return getInputDispatchingTimeoutLocked(r.app);
5292 }
5293
5294 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005295 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005296 }
5297
Wale Ogunwalef6733932018-06-27 05:14:34 -07005298 /**
5299 * Decide based on the configuration whether we should show the ANR,
5300 * crash, etc dialogs. The idea is that if there is no affordance to
5301 * press the on-screen buttons, or the user experience would be more
5302 * greatly impacted than the crash itself, we shouldn't show the dialog.
5303 *
5304 * A thought: SystemUI might also want to get told about this, the Power
5305 * dialog / global actions also might want different behaviors.
5306 */
5307 private void updateShouldShowDialogsLocked(Configuration config) {
5308 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5309 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5310 && config.navigation == Configuration.NAVIGATION_NONAV);
5311 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5312 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5313 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5314 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5315 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5316 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5317 HIDE_ERROR_DIALOGS, 0) != 0;
5318 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5319 }
5320
5321 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5322 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5323 FONT_SCALE, 1.0f, userId);
5324
5325 synchronized (this) {
5326 if (getGlobalConfiguration().fontScale == scaleFactor) {
5327 return;
5328 }
5329
5330 final Configuration configuration
5331 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5332 configuration.fontScale = scaleFactor;
5333 updatePersistentConfiguration(configuration, userId);
5334 }
5335 }
5336
5337 // Actually is sleeping or shutting down or whatever else in the future
5338 // is an inactive state.
5339 boolean isSleepingOrShuttingDownLocked() {
5340 return isSleepingLocked() || mShuttingDown;
5341 }
5342
5343 boolean isSleepingLocked() {
5344 return mSleeping;
5345 }
5346
Riddle Hsu16567132018-08-16 21:37:47 +08005347 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005348 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005349 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005350 if (task.isActivityTypeStandard()) {
5351 if (mCurAppTimeTracker != r.appTimeTracker) {
5352 // We are switching app tracking. Complete the current one.
5353 if (mCurAppTimeTracker != null) {
5354 mCurAppTimeTracker.stop();
5355 mH.obtainMessage(
5356 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005357 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 mCurAppTimeTracker = null;
5359 }
5360 if (r.appTimeTracker != null) {
5361 mCurAppTimeTracker = r.appTimeTracker;
5362 startTimeTrackingFocusedActivityLocked();
5363 }
5364 } else {
5365 startTimeTrackingFocusedActivityLocked();
5366 }
5367 } else {
5368 r.appTimeTracker = null;
5369 }
5370 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5371 // TODO: Probably not, because we don't want to resume voice on switching
5372 // back to this activity
5373 if (task.voiceInteractor != null) {
5374 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5375 } else {
5376 finishRunningVoiceLocked();
5377
5378 if (mLastResumedActivity != null) {
5379 final IVoiceInteractionSession session;
5380
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005381 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005382 if (lastResumedActivityTask != null
5383 && lastResumedActivityTask.voiceSession != null) {
5384 session = lastResumedActivityTask.voiceSession;
5385 } else {
5386 session = mLastResumedActivity.voiceSession;
5387 }
5388
5389 if (session != null) {
5390 // We had been in a voice interaction session, but now focused has
5391 // move to something different. Just finish the session, we can't
5392 // return to it and retain the proper state and synchronization with
5393 // the voice interaction service.
5394 finishVoiceTask(session);
5395 }
5396 }
5397 }
5398
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005399 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5400 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005401 }
5402 updateResumedAppTrace(r);
5403 mLastResumedActivity = r;
5404
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005405 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005406
5407 applyUpdateLockStateLocked(r);
5408 applyUpdateVrModeLocked(r);
5409
5410 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005411 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005412 r == null ? "NULL" : r.shortComponentName,
5413 reason);
5414 }
5415
5416 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5417 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005418 final ActivityTaskManagerInternal.SleepToken token =
5419 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005420 updateSleepIfNeededLocked();
5421 return token;
5422 }
5423 }
5424
5425 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005426 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005427 final boolean wasSleeping = mSleeping;
5428 boolean updateOomAdj = false;
5429
5430 if (!shouldSleep) {
5431 // If wasSleeping is true, we need to wake up activity manager state from when
5432 // we started sleeping. In either case, we need to apply the sleep tokens, which
5433 // will wake up stacks or put them to sleep as appropriate.
5434 if (wasSleeping) {
5435 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005436 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5437 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005438 startTimeTrackingFocusedActivityLocked();
5439 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005440 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005441 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5442 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005443 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005444 if (wasSleeping) {
5445 updateOomAdj = true;
5446 }
5447 } else if (!mSleeping && shouldSleep) {
5448 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005449 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5450 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 if (mCurAppTimeTracker != null) {
5452 mCurAppTimeTracker.stop();
5453 }
5454 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005455 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005456 mStackSupervisor.goingToSleepLocked();
5457 updateResumedAppTrace(null /* resumed */);
5458 updateOomAdj = true;
5459 }
5460 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005461 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005462 }
5463 }
5464
5465 void updateOomAdj() {
5466 mH.post(mAmInternal::updateOomAdj);
5467 }
5468
Wale Ogunwale53783742018-09-16 10:21:51 -07005469 void updateCpuStats() {
5470 mH.post(mAmInternal::updateCpuStats);
5471 }
5472
Hui Yu03d12402018-12-06 18:00:37 -08005473 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5474 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005475 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5476 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005477 mH.sendMessage(m);
5478 }
5479
Hui Yu03d12402018-12-06 18:00:37 -08005480 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005481 ComponentName taskRoot = null;
5482 final TaskRecord task = activity.getTaskRecord();
5483 if (task != null) {
5484 final ActivityRecord rootActivity = task.getRootActivity();
5485 if (rootActivity != null) {
5486 taskRoot = rootActivity.mActivityComponent;
5487 }
5488 }
5489
Hui Yu03d12402018-12-06 18:00:37 -08005490 final Message m = PooledLambda.obtainMessage(
5491 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005492 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005493 mH.sendMessage(m);
5494 }
5495
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005496 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5497 String hostingType) {
5498 try {
5499 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5500 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5501 + activity.processName);
5502 }
5503 // Post message to start process to avoid possible deadlock of calling into AMS with the
5504 // ATMS lock held.
5505 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5506 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5507 isTop, hostingType, activity.intent.getComponent());
5508 mH.sendMessage(m);
5509 } finally {
5510 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5511 }
5512 }
5513
Wale Ogunwale53783742018-09-16 10:21:51 -07005514 void setBooting(boolean booting) {
5515 mAmInternal.setBooting(booting);
5516 }
5517
5518 boolean isBooting() {
5519 return mAmInternal.isBooting();
5520 }
5521
5522 void setBooted(boolean booted) {
5523 mAmInternal.setBooted(booted);
5524 }
5525
5526 boolean isBooted() {
5527 return mAmInternal.isBooted();
5528 }
5529
5530 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5531 mH.post(() -> {
5532 if (finishBooting) {
5533 mAmInternal.finishBooting();
5534 }
5535 if (enableScreen) {
5536 mInternal.enableScreenAfterBoot(isBooted());
5537 }
5538 });
5539 }
5540
5541 void setHeavyWeightProcess(ActivityRecord root) {
5542 mHeavyWeightProcess = root.app;
5543 final Message m = PooledLambda.obtainMessage(
5544 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005545 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005546 mH.sendMessage(m);
5547 }
5548
5549 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5550 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5551 return;
5552 }
5553
5554 mHeavyWeightProcess = null;
5555 final Message m = PooledLambda.obtainMessage(
5556 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5557 proc.mUserId);
5558 mH.sendMessage(m);
5559 }
5560
5561 private void cancelHeavyWeightProcessNotification(int userId) {
5562 final INotificationManager inm = NotificationManager.getService();
5563 if (inm == null) {
5564 return;
5565 }
5566 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005567 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005568 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5569 } catch (RuntimeException e) {
5570 Slog.w(TAG, "Error canceling notification for service", e);
5571 } catch (RemoteException e) {
5572 }
5573
5574 }
5575
5576 private void postHeavyWeightProcessNotification(
5577 WindowProcessController proc, Intent intent, int userId) {
5578 if (proc == null) {
5579 return;
5580 }
5581
5582 final INotificationManager inm = NotificationManager.getService();
5583 if (inm == null) {
5584 return;
5585 }
5586
5587 try {
5588 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5589 String text = mContext.getString(R.string.heavy_weight_notification,
5590 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5591 Notification notification =
5592 new Notification.Builder(context,
5593 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5594 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5595 .setWhen(0)
5596 .setOngoing(true)
5597 .setTicker(text)
5598 .setColor(mContext.getColor(
5599 com.android.internal.R.color.system_notification_accent_color))
5600 .setContentTitle(text)
5601 .setContentText(
5602 mContext.getText(R.string.heavy_weight_notification_detail))
5603 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5604 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5605 new UserHandle(userId)))
5606 .build();
5607 try {
5608 inm.enqueueNotificationWithTag("android", "android", null,
5609 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5610 } catch (RuntimeException e) {
5611 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5612 } catch (RemoteException e) {
5613 }
5614 } catch (PackageManager.NameNotFoundException e) {
5615 Slog.w(TAG, "Unable to create context for heavy notification", e);
5616 }
5617
5618 }
5619
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005620 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5621 IBinder token, String resultWho, int requestCode, Intent[] intents,
5622 String[] resolvedTypes, int flags, Bundle bOptions) {
5623
5624 ActivityRecord activity = null;
5625 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5626 activity = ActivityRecord.isInStackLocked(token);
5627 if (activity == null) {
5628 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5629 return null;
5630 }
5631 if (activity.finishing) {
5632 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5633 return null;
5634 }
5635 }
5636
5637 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5638 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5639 bOptions);
5640 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5641 if (noCreate) {
5642 return rec;
5643 }
5644 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5645 if (activity.pendingResults == null) {
5646 activity.pendingResults = new HashSet<>();
5647 }
5648 activity.pendingResults.add(rec.ref);
5649 }
5650 return rec;
5651 }
5652
Andrii Kulian52d255c2018-07-13 11:32:19 -07005653 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005654 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005655 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005656 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5657 mCurAppTimeTracker.start(resumedActivity.packageName);
5658 }
5659 }
5660
5661 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5662 if (mTracedResumedActivity != null) {
5663 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5664 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5665 }
5666 if (resumed != null) {
5667 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5668 constructResumedTraceName(resumed.packageName), 0);
5669 }
5670 mTracedResumedActivity = resumed;
5671 }
5672
5673 private String constructResumedTraceName(String packageName) {
5674 return "focused app: " + packageName;
5675 }
5676
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005677 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005678 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005679 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005680 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005681 // mainStack is null during startup.
5682 if (mainStack != null) {
5683 if (changes != 0 && starting == null) {
5684 // If the configuration changed, and the caller is not already
5685 // in the process of starting an activity, then find the top
5686 // activity to check if its configuration needs to change.
5687 starting = mainStack.topRunningActivityLocked();
5688 }
5689
5690 if (starting != null) {
5691 kept = starting.ensureActivityConfiguration(changes,
5692 false /* preserveWindow */);
5693 // And we need to make sure at this point that all other activities
5694 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005695 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005696 !PRESERVE_WINDOWS);
5697 }
5698 }
5699
5700 return kept;
5701 }
5702
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005703 void scheduleAppGcsLocked() {
5704 mH.post(() -> mAmInternal.scheduleAppGcs());
5705 }
5706
Wale Ogunwale53783742018-09-16 10:21:51 -07005707 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5708 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5709 }
5710
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005711 /**
5712 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5713 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5714 * on demand.
5715 */
5716 IPackageManager getPackageManager() {
5717 return AppGlobals.getPackageManager();
5718 }
5719
5720 PackageManagerInternal getPackageManagerInternalLocked() {
5721 if (mPmInternal == null) {
5722 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5723 }
5724 return mPmInternal;
5725 }
5726
Hai Zhangf4da9be2019-05-01 13:46:06 +08005727 PermissionPolicyInternal getPermissionPolicyInternal() {
5728 if (mPermissionPolicyInternal == null) {
5729 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5730 }
5731 return mPermissionPolicyInternal;
5732 }
5733
Wale Ogunwale008163e2018-07-23 23:11:08 -07005734 AppWarnings getAppWarningsLocked() {
5735 return mAppWarnings;
5736 }
5737
Wale Ogunwale214f3482018-10-04 11:00:47 -07005738 Intent getHomeIntent() {
5739 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5740 intent.setComponent(mTopComponent);
5741 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5742 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5743 intent.addCategory(Intent.CATEGORY_HOME);
5744 }
5745 return intent;
5746 }
5747
Chilun2ef71f72018-11-16 17:57:15 +08005748 /**
5749 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5750 * activities.
5751 *
5752 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5753 * component defined in config_secondaryHomeComponent.
5754 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5755 */
5756 Intent getSecondaryHomeIntent(String preferredPackage) {
5757 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005758 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5759 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5760 if (preferredPackage == null || useSystemProvidedLauncher) {
5761 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005762 final String secondaryHomeComponent = mContext.getResources().getString(
5763 com.android.internal.R.string.config_secondaryHomeComponent);
5764 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5765 } else {
5766 intent.setPackage(preferredPackage);
5767 }
5768 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5769 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5770 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5771 }
5772 return intent;
5773 }
5774
Wale Ogunwale214f3482018-10-04 11:00:47 -07005775 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5776 if (info == null) return null;
5777 ApplicationInfo newInfo = new ApplicationInfo(info);
5778 newInfo.initForUser(userId);
5779 return newInfo;
5780 }
5781
Wale Ogunwale9c103022018-10-18 07:44:54 -07005782 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005783 if (uid == SYSTEM_UID) {
5784 // The system gets to run in any process. If there are multiple processes with the same
5785 // uid, just pick the first (this should never happen).
5786 final SparseArray<WindowProcessController> procs =
5787 mProcessNames.getMap().get(processName);
5788 if (procs == null) return null;
5789 final int procCount = procs.size();
5790 for (int i = 0; i < procCount; i++) {
5791 final int procUid = procs.keyAt(i);
5792 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5793 // Don't use an app process or different user process for system component.
5794 continue;
5795 }
5796 return procs.valueAt(i);
5797 }
5798 }
5799
5800 return mProcessNames.get(processName, uid);
5801 }
5802
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005803 WindowProcessController getProcessController(IApplicationThread thread) {
5804 if (thread == null) {
5805 return null;
5806 }
5807
5808 final IBinder threadBinder = thread.asBinder();
5809 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5810 for (int i = pmap.size()-1; i >= 0; i--) {
5811 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5812 for (int j = procs.size() - 1; j >= 0; j--) {
5813 final WindowProcessController proc = procs.valueAt(j);
5814 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5815 return proc;
5816 }
5817 }
5818 }
5819
5820 return null;
5821 }
5822
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005823 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005824 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005825 if (proc == null) return null;
5826 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5827 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005828 }
5829 return null;
5830 }
5831
Riddle Hsua0536432019-02-16 00:38:59 +08005832 int getUidState(int uid) {
5833 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005834 }
5835
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005836 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005837 // A uid is considered to be foreground if it has a visible non-toast window.
5838 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005839 }
5840
Ricky Wai96f5c352019-04-10 18:40:17 +01005841 boolean isDeviceOwner(int uid) {
5842 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005843 }
5844
Ricky Wai96f5c352019-04-10 18:40:17 +01005845 void setDeviceOwnerUid(int uid) {
5846 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005847 }
5848
Wale Ogunwale9de19442018-10-18 19:05:03 -07005849 /**
5850 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5851 * the whitelist
5852 */
5853 String getPendingTempWhitelistTagForUidLocked(int uid) {
5854 return mPendingTempWhitelist.get(uid);
5855 }
5856
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005857 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5858 if (true || Build.IS_USER) {
5859 return;
5860 }
5861
5862 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5863 StrictMode.allowThreadDiskWrites();
5864 try {
5865 File tracesDir = new File("/data/anr");
5866 File tracesFile = null;
5867 try {
5868 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5869
5870 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005871 String timeString =
5872 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5873 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005874 sb.append(": ");
5875 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5876 sb.append(" since ");
5877 sb.append(msg);
5878 FileOutputStream fos = new FileOutputStream(tracesFile);
5879 fos.write(sb.toString().getBytes());
5880 if (app == null) {
5881 fos.write("\n*** No application process!".getBytes());
5882 }
5883 fos.close();
5884 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5885 } catch (IOException e) {
5886 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5887 return;
5888 }
5889
5890 if (app != null && app.getPid() > 0) {
5891 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5892 firstPids.add(app.getPid());
5893 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5894 }
5895
5896 File lastTracesFile = null;
5897 File curTracesFile = null;
5898 for (int i=9; i>=0; i--) {
5899 String name = String.format(Locale.US, "slow%02d.txt", i);
5900 curTracesFile = new File(tracesDir, name);
5901 if (curTracesFile.exists()) {
5902 if (lastTracesFile != null) {
5903 curTracesFile.renameTo(lastTracesFile);
5904 } else {
5905 curTracesFile.delete();
5906 }
5907 }
5908 lastTracesFile = curTracesFile;
5909 }
5910 tracesFile.renameTo(curTracesFile);
5911 } finally {
5912 StrictMode.setThreadPolicy(oldPolicy);
5913 }
5914 }
5915
Michal Karpinskida34cd42019-04-02 19:46:52 +01005916 boolean isAssociatedCompanionApp(int userId, int uid) {
5917 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5918 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005919 return false;
5920 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005921 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005922 }
5923
Issei Suzuki734bc942019-06-05 13:59:52 +02005924 void notifySingleTaskDisplayEmpty(int displayId) {
5925 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5926 }
5927
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005928 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005929 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005930
5931
Wale Ogunwale98875612018-10-12 07:53:02 -07005932 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5933 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005934
Riddle Hsud93a6c42018-11-29 21:50:06 +08005935 H(Looper looper) {
5936 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005937 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005938
5939 @Override
5940 public void handleMessage(Message msg) {
5941 switch (msg.what) {
5942 case REPORT_TIME_TRACKER_MSG: {
5943 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5944 tracker.deliverResult(mContext);
5945 } break;
5946 }
5947 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005948 }
5949
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005950 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005951 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005952
5953 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005954 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005955 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005956
5957 @Override
5958 public void handleMessage(Message msg) {
5959 switch (msg.what) {
5960 case DISMISS_DIALOG_UI_MSG: {
5961 final Dialog d = (Dialog) msg.obj;
5962 d.dismiss();
5963 break;
5964 }
5965 }
5966 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005967 }
5968
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005969 final class LocalService extends ActivityTaskManagerInternal {
5970 @Override
5971 public SleepToken acquireSleepToken(String tag, int displayId) {
5972 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005973 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005974 }
5975
5976 @Override
5977 public ComponentName getHomeActivityForUser(int userId) {
5978 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005979 final ActivityRecord homeActivity =
5980 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005981 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005982 }
5983 }
5984
5985 @Override
5986 public void onLocalVoiceInteractionStarted(IBinder activity,
5987 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5988 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005989 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005990 }
5991 }
5992
5993 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005994 public void notifyAppTransitionStarting(SparseIntArray reasons,
5995 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005996 synchronized (mGlobalLock) {
5997 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5998 reasons, timestamp);
5999 }
6000 }
6001
6002 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006003 public void notifySingleTaskDisplayDrawn(int displayId) {
6004 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6005 }
6006
6007 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008 public void notifyAppTransitionFinished() {
6009 synchronized (mGlobalLock) {
6010 mStackSupervisor.notifyAppTransitionDone();
6011 }
6012 }
6013
6014 @Override
6015 public void notifyAppTransitionCancelled() {
6016 synchronized (mGlobalLock) {
6017 mStackSupervisor.notifyAppTransitionDone();
6018 }
6019 }
6020
6021 @Override
6022 public List<IBinder> getTopVisibleActivities() {
6023 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006024 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006025 }
6026 }
6027
6028 @Override
6029 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6030 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006031 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006032 }
6033 }
6034
6035 @Override
6036 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6037 Bundle bOptions) {
6038 Preconditions.checkNotNull(intents, "intents");
6039 final String[] resolvedTypes = new String[intents.length];
6040
6041 // UID of the package on user userId.
6042 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6043 // packageUid may not be initialized.
6044 int packageUid = 0;
6045 final long ident = Binder.clearCallingIdentity();
6046
6047 try {
6048 for (int i = 0; i < intents.length; i++) {
6049 resolvedTypes[i] =
6050 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6051 }
6052
6053 packageUid = AppGlobals.getPackageManager().getPackageUid(
6054 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6055 } catch (RemoteException e) {
6056 // Shouldn't happen.
6057 } finally {
6058 Binder.restoreCallingIdentity(ident);
6059 }
6060
Riddle Hsu591bf612019-02-14 17:55:31 +08006061 return getActivityStartController().startActivitiesInPackage(
6062 packageUid, packageName,
6063 intents, resolvedTypes, null /* resultTo */,
6064 SafeActivityOptions.fromBundle(bOptions), userId,
6065 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6066 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006067 }
6068
6069 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006070 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6071 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6072 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6073 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006074 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006075 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006076 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6077 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6078 userId, validateIncomingUser, originatingPendingIntent,
6079 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006080 }
6081 }
6082
6083 @Override
6084 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6085 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6086 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6087 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006088 PendingIntentRecord originatingPendingIntent,
6089 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006090 synchronized (mGlobalLock) {
6091 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6092 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6093 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006094 validateIncomingUser, originatingPendingIntent,
6095 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006096 }
6097 }
6098
6099 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006100 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6101 Intent intent, Bundle options, int userId) {
6102 return ActivityTaskManagerService.this.startActivityAsUser(
6103 caller, callerPacakge, intent,
6104 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6105 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6106 false /*validateIncomingUser*/);
6107 }
6108
6109 @Override
lumark588a3e82018-07-20 18:53:54 +08006110 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006111 synchronized (mGlobalLock) {
6112
6113 // We might change the visibilities here, so prepare an empty app transition which
6114 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006115 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006116 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006117 if (activityDisplay == null) {
6118 return;
6119 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006120 final DisplayContent dc = activityDisplay.mDisplayContent;
6121 final boolean wasTransitionSet =
6122 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006124 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006125 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006126 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127
6128 // If there was a transition set already we don't want to interfere with it as we
6129 // might be starting it too early.
6130 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006131 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006132 }
6133 }
6134 if (callback != null) {
6135 callback.run();
6136 }
6137 }
6138
6139 @Override
6140 public void notifyKeyguardTrustedChanged() {
6141 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006142 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006143 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006144 }
6145 }
6146 }
6147
6148 /**
6149 * Called after virtual display Id is updated by
6150 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6151 * {@param vrVr2dDisplayId}.
6152 */
6153 @Override
6154 public void setVr2dDisplayId(int vr2dDisplayId) {
6155 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6156 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006157 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006158 }
6159 }
6160
6161 @Override
6162 public void setFocusedActivity(IBinder token) {
6163 synchronized (mGlobalLock) {
6164 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6165 if (r == null) {
6166 throw new IllegalArgumentException(
6167 "setFocusedActivity: No activity record matching token=" + token);
6168 }
Louis Chang19443452018-10-09 12:10:21 +08006169 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006170 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006171 }
6172 }
6173 }
6174
6175 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006177 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179
6180 @Override
6181 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006182 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006183 }
6184
6185 @Override
6186 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006187 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006188 }
6189
6190 @Override
6191 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6192 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6193 }
6194
6195 @Override
6196 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006197 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006199
6200 @Override
6201 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6202 synchronized (mGlobalLock) {
6203 mActiveVoiceInteractionServiceComponent = component;
6204 }
6205 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006206
6207 @Override
6208 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6209 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6210 return;
6211 }
6212 synchronized (mGlobalLock) {
6213 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6214 if (types == null) {
6215 if (uid < 0) {
6216 return;
6217 }
6218 types = new ArrayMap<>();
6219 mAllowAppSwitchUids.put(userId, types);
6220 }
6221 if (uid < 0) {
6222 types.remove(type);
6223 } else {
6224 types.put(type, uid);
6225 }
6226 }
6227 }
6228
6229 @Override
6230 public void onUserStopped(int userId) {
6231 synchronized (mGlobalLock) {
6232 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6233 mAllowAppSwitchUids.remove(userId);
6234 }
6235 }
6236
6237 @Override
6238 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6239 synchronized (mGlobalLock) {
6240 return ActivityTaskManagerService.this.isGetTasksAllowed(
6241 caller, callingPid, callingUid);
6242 }
6243 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006244
Riddle Hsua0536432019-02-16 00:38:59 +08006245 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006246 @Override
6247 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006248 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006249 mProcessNames.put(proc.mName, proc.mUid, proc);
6250 }
6251 }
6252
Riddle Hsua0536432019-02-16 00:38:59 +08006253 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006254 @Override
6255 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006256 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006257 mProcessNames.remove(name, uid);
6258 }
6259 }
6260
Riddle Hsua0536432019-02-16 00:38:59 +08006261 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006262 @Override
6263 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006264 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006265 if (proc == mHomeProcess) {
6266 mHomeProcess = null;
6267 }
6268 if (proc == mPreviousProcess) {
6269 mPreviousProcess = null;
6270 }
6271 }
6272 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006273
Riddle Hsua0536432019-02-16 00:38:59 +08006274 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006275 @Override
6276 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006277 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006278 return mTopProcessState;
6279 }
6280 }
6281
Riddle Hsua0536432019-02-16 00:38:59 +08006282 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006283 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006284 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006285 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006286 return proc == mHeavyWeightProcess;
6287 }
6288 }
6289
Riddle Hsua0536432019-02-16 00:38:59 +08006290 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006291 @Override
6292 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006293 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006294 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6295 }
6296 }
6297
6298 @Override
6299 public void finishHeavyWeightApp() {
6300 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006301 if (mHeavyWeightProcess != null) {
6302 mHeavyWeightProcess.finishActivities();
6303 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006304 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6305 mHeavyWeightProcess);
6306 }
6307 }
6308
Riddle Hsua0536432019-02-16 00:38:59 +08006309 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006310 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006311 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006312 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006313 return isSleepingLocked();
6314 }
6315 }
6316
6317 @Override
6318 public boolean isShuttingDown() {
6319 synchronized (mGlobalLock) {
6320 return mShuttingDown;
6321 }
6322 }
6323
6324 @Override
6325 public boolean shuttingDown(boolean booted, int timeout) {
6326 synchronized (mGlobalLock) {
6327 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006328 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006329 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006330 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006331 return mStackSupervisor.shutdownLocked(timeout);
6332 }
6333 }
6334
6335 @Override
6336 public void enableScreenAfterBoot(boolean booted) {
6337 synchronized (mGlobalLock) {
6338 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6339 SystemClock.uptimeMillis());
6340 mWindowManager.enableScreenAfterBoot();
6341 updateEventDispatchingLocked(booted);
6342 }
6343 }
6344
6345 @Override
6346 public boolean showStrictModeViolationDialog() {
6347 synchronized (mGlobalLock) {
6348 return mShowDialogs && !mSleeping && !mShuttingDown;
6349 }
6350 }
6351
6352 @Override
6353 public void showSystemReadyErrorDialogsIfNeeded() {
6354 synchronized (mGlobalLock) {
6355 try {
6356 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6357 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6358 + " data partition or your device will be unstable.");
6359 mUiHandler.post(() -> {
6360 if (mShowDialogs) {
6361 AlertDialog d = new BaseErrorDialog(mUiContext);
6362 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6363 d.setCancelable(false);
6364 d.setTitle(mUiContext.getText(R.string.android_system_label));
6365 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6366 d.setButton(DialogInterface.BUTTON_POSITIVE,
6367 mUiContext.getText(R.string.ok),
6368 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6369 d.show();
6370 }
6371 });
6372 }
6373 } catch (RemoteException e) {
6374 }
6375
6376 if (!Build.isBuildConsistent()) {
6377 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6378 mUiHandler.post(() -> {
6379 if (mShowDialogs) {
6380 AlertDialog d = new BaseErrorDialog(mUiContext);
6381 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6382 d.setCancelable(false);
6383 d.setTitle(mUiContext.getText(R.string.android_system_label));
6384 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6385 d.setButton(DialogInterface.BUTTON_POSITIVE,
6386 mUiContext.getText(R.string.ok),
6387 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6388 d.show();
6389 }
6390 });
6391 }
6392 }
6393 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006394
6395 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006396 public void onProcessMapped(int pid, WindowProcessController proc) {
6397 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006398 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006399 }
6400 }
6401
6402 @Override
6403 public void onProcessUnMapped(int pid) {
6404 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006405 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006406 }
6407 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006408
6409 @Override
6410 public void onPackageDataCleared(String name) {
6411 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006412 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006413 mAppWarnings.onPackageDataCleared(name);
6414 }
6415 }
6416
6417 @Override
6418 public void onPackageUninstalled(String name) {
6419 synchronized (mGlobalLock) {
6420 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006421 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006422 }
6423 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006424
6425 @Override
6426 public void onPackageAdded(String name, boolean replacing) {
6427 synchronized (mGlobalLock) {
6428 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6429 }
6430 }
6431
6432 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006433 public void onPackageReplaced(ApplicationInfo aInfo) {
6434 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006435 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006436 }
6437 }
6438
6439 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006440 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6441 synchronized (mGlobalLock) {
6442 return compatibilityInfoForPackageLocked(ai);
6443 }
6444 }
6445
Yunfan Chen75157d72018-07-27 14:47:21 +09006446 /**
6447 * Set the corresponding display information for the process global configuration. To be
6448 * called when we need to show IME on a different display.
6449 *
6450 * @param pid The process id associated with the IME window.
6451 * @param displayId The ID of the display showing the IME.
6452 */
6453 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006454 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006455 // Don't update process-level configuration for Multi-Client IME process since other
6456 // IMEs on other displays will also receive this configuration change due to IME
6457 // services use the same application config/context.
6458 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006459
Yunfan Chen75157d72018-07-27 14:47:21 +09006460 if (pid == MY_PID || pid < 0) {
6461 if (DEBUG_CONFIGURATION) {
6462 Slog.w(TAG,
6463 "Trying to update display configuration for system/invalid process.");
6464 }
6465 return;
6466 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006467 synchronized (mGlobalLock) {
6468 final ActivityDisplay activityDisplay =
6469 mRootActivityContainer.getActivityDisplay(displayId);
6470 if (activityDisplay == null) {
6471 // Call might come when display is not yet added or has been removed.
6472 if (DEBUG_CONFIGURATION) {
6473 Slog.w(TAG, "Trying to update display configuration for non-existing "
6474 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006475 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006476 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006477 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006478 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006479 if (process == null) {
6480 if (DEBUG_CONFIGURATION) {
6481 Slog.w(TAG, "Trying to update display configuration for invalid "
6482 + "process, pid=" + pid);
6483 }
6484 return;
6485 }
lumarkddc77fb2019-06-27 22:22:23 +08006486 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006487 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6488 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006489 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006490
6491 @Override
6492 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006493 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006494 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006495 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6496 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006497 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006498 }
6499 }
6500 }
6501
6502 @Override
6503 public void clearPendingResultForActivity(IBinder activityToken,
6504 WeakReference<PendingIntentRecord> pir) {
6505 synchronized (mGlobalLock) {
6506 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6507 if (r != null && r.pendingResults != null) {
6508 r.pendingResults.remove(pir);
6509 }
6510 }
6511 }
6512
6513 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006514 public ActivityTokens getTopActivityForTask(int taskId) {
6515 synchronized (mGlobalLock) {
6516 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6517 if (taskRecord == null) {
6518 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6519 + " Requested task not found");
6520 return null;
6521 }
6522 final ActivityRecord activity = taskRecord.getTopActivity();
6523 if (activity == null) {
6524 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6525 + " Requested activity not found");
6526 return null;
6527 }
6528 if (!activity.attachedToProcess()) {
6529 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6530 + activity);
6531 return null;
6532 }
6533 return new ActivityTokens(activity.appToken, activity.assistToken,
6534 activity.app.getThread());
6535 }
6536 }
6537
6538 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006539 public IIntentSender getIntentSender(int type, String packageName,
6540 int callingUid, int userId, IBinder token, String resultWho,
6541 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6542 Bundle bOptions) {
6543 synchronized (mGlobalLock) {
6544 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6545 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6546 }
6547 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006548
6549 @Override
6550 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6551 synchronized (mGlobalLock) {
6552 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6553 if (r == null) {
6554 return null;
6555 }
6556 if (r.mServiceConnectionsHolder == null) {
6557 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6558 ActivityTaskManagerService.this, r);
6559 }
6560
6561 return r.mServiceConnectionsHolder;
6562 }
6563 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006564
6565 @Override
6566 public Intent getHomeIntent() {
6567 synchronized (mGlobalLock) {
6568 return ActivityTaskManagerService.this.getHomeIntent();
6569 }
6570 }
6571
6572 @Override
6573 public boolean startHomeActivity(int userId, String reason) {
6574 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006575 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006576 }
6577 }
6578
6579 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006580 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006581 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006582 synchronized (mGlobalLock) {
6583 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006584 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006585 }
Chilun8b1f1be2019-03-13 17:14:36 +08006586 }
6587
6588 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006589 public boolean startHomeOnAllDisplays(int userId, String reason) {
6590 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006591 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006592 }
6593 }
6594
Riddle Hsua0536432019-02-16 00:38:59 +08006595 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006596 @Override
6597 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006598 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006599 if (mFactoryTest == FACTORY_TEST_OFF) {
6600 return false;
6601 }
6602 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6603 && wpc.mName.equals(mTopComponent.getPackageName())) {
6604 return true;
6605 }
6606 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6607 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6608 }
6609 }
6610
6611 @Override
6612 public void updateTopComponentForFactoryTest() {
6613 synchronized (mGlobalLock) {
6614 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6615 return;
6616 }
6617 final ResolveInfo ri = mContext.getPackageManager()
6618 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6619 final CharSequence errorMsg;
6620 if (ri != null) {
6621 final ActivityInfo ai = ri.activityInfo;
6622 final ApplicationInfo app = ai.applicationInfo;
6623 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6624 mTopAction = Intent.ACTION_FACTORY_TEST;
6625 mTopData = null;
6626 mTopComponent = new ComponentName(app.packageName, ai.name);
6627 errorMsg = null;
6628 } else {
6629 errorMsg = mContext.getResources().getText(
6630 com.android.internal.R.string.factorytest_not_system);
6631 }
6632 } else {
6633 errorMsg = mContext.getResources().getText(
6634 com.android.internal.R.string.factorytest_no_action);
6635 }
6636 if (errorMsg == null) {
6637 return;
6638 }
6639
6640 mTopAction = null;
6641 mTopData = null;
6642 mTopComponent = null;
6643 mUiHandler.post(() -> {
6644 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6645 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006646 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006647 });
6648 }
6649 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006650
Riddle Hsua0536432019-02-16 00:38:59 +08006651 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006652 @Override
6653 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6654 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006655 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006656 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006657 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006658
6659 wpc.clearRecentTasks();
6660 wpc.clearActivities();
6661
6662 if (wpc.isInstrumenting()) {
6663 finishInstrumentationCallback.run();
6664 }
6665
Jorim Jaggid0752812018-10-16 16:07:20 +02006666 if (!restarting && hasVisibleActivities) {
6667 mWindowManager.deferSurfaceLayout();
6668 try {
6669 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6670 // If there was nothing to resume, and we are not already restarting
6671 // this process, but there is a visible activity that is hosted by the
6672 // process...then make sure all visible activities are running, taking
6673 // care of restarting this process.
6674 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6675 !PRESERVE_WINDOWS);
6676 }
6677 } finally {
6678 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006679 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006680 }
6681 }
6682 }
6683
6684 @Override
6685 public void closeSystemDialogs(String reason) {
6686 enforceNotIsolatedCaller("closeSystemDialogs");
6687
6688 final int pid = Binder.getCallingPid();
6689 final int uid = Binder.getCallingUid();
6690 final long origId = Binder.clearCallingIdentity();
6691 try {
6692 synchronized (mGlobalLock) {
6693 // Only allow this from foreground processes, so that background
6694 // applications can't abuse it to prevent system UI from being shown.
6695 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006696 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006697 if (!proc.isPerceptible()) {
6698 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6699 + " from background process " + proc);
6700 return;
6701 }
6702 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006703 mWindowManager.closeSystemDialogs(reason);
6704
Wale Ogunwaled32da472018-11-16 07:19:28 -08006705 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006707 // Call into AM outside the synchronized block.
6708 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709 } finally {
6710 Binder.restoreCallingIdentity(origId);
6711 }
6712 }
6713
6714 @Override
6715 public void cleanupDisabledPackageComponents(
6716 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6717 synchronized (mGlobalLock) {
6718 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006719 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006720 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006721 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006722 mStackSupervisor.scheduleIdleLocked();
6723 }
6724
6725 // Clean-up disabled tasks
6726 getRecentTasks().cleanupDisabledPackageTasksLocked(
6727 packageName, disabledClasses, userId);
6728 }
6729 }
6730
6731 @Override
6732 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6733 int userId) {
6734 synchronized (mGlobalLock) {
6735
6736 boolean didSomething =
6737 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006738 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006739 null, doit, evenPersistent, userId);
6740 return didSomething;
6741 }
6742 }
6743
6744 @Override
6745 public void resumeTopActivities(boolean scheduleIdle) {
6746 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006747 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748 if (scheduleIdle) {
6749 mStackSupervisor.scheduleIdleLocked();
6750 }
6751 }
6752 }
6753
Riddle Hsua0536432019-02-16 00:38:59 +08006754 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006755 @Override
6756 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006757 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006758 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6759 }
6760 }
6761
Riddle Hsua0536432019-02-16 00:38:59 +08006762 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 @Override
6764 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006765 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006766 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 }
6768 }
6769
6770 @Override
6771 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6772 try {
6773 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6774 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6775 }
6776 } catch (RemoteException ex) {
6777 throw new SecurityException("Fail to check is caller a privileged app", ex);
6778 }
6779
6780 synchronized (mGlobalLock) {
6781 final long ident = Binder.clearCallingIdentity();
6782 try {
6783 if (mAmInternal.shouldConfirmCredentials(userId)) {
6784 if (mKeyguardController.isKeyguardLocked()) {
6785 // Showing launcher to avoid user entering credential twice.
6786 startHomeActivity(currentUserId, "notifyLockedProfile");
6787 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006788 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006789 }
6790 } finally {
6791 Binder.restoreCallingIdentity(ident);
6792 }
6793 }
6794 }
6795
6796 @Override
6797 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6798 mAmInternal.enforceCallingPermission(
6799 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6800
6801 synchronized (mGlobalLock) {
6802 final long ident = Binder.clearCallingIdentity();
6803 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006804 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6805 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6808 UserHandle.CURRENT);
6809 } finally {
6810 Binder.restoreCallingIdentity(ident);
6811 }
6812 }
6813 }
6814
6815 @Override
6816 public void writeActivitiesToProto(ProtoOutputStream proto) {
6817 synchronized (mGlobalLock) {
6818 // The output proto of "activity --proto activities"
6819 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006820 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006821 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6822 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 }
6824 }
6825
6826 @Override
6827 public void saveANRState(String reason) {
6828 synchronized (mGlobalLock) {
6829 final StringWriter sw = new StringWriter();
6830 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6831 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6832 if (reason != null) {
6833 pw.println(" Reason: " + reason);
6834 }
6835 pw.println();
6836 getActivityStartController().dump(pw, " ", null);
6837 pw.println();
6838 pw.println("-------------------------------------------------------------------------------");
6839 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6840 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6841 "" /* header */);
6842 pw.println();
6843 pw.close();
6844
6845 mLastANRState = sw.toString();
6846 }
6847 }
6848
6849 @Override
6850 public void clearSavedANRState() {
6851 synchronized (mGlobalLock) {
6852 mLastANRState = null;
6853 }
6854 }
6855
6856 @Override
6857 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6858 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6859 synchronized (mGlobalLock) {
6860 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6861 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6862 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6863 dumpLastANRLocked(pw);
6864 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6865 dumpLastANRTracesLocked(pw);
6866 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6867 dumpActivityStarterLocked(pw, dumpPackage);
6868 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6869 dumpActivityContainersLocked(pw);
6870 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6871 if (getRecentTasks() != null) {
6872 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6873 }
6874 }
6875 }
6876 }
6877
6878 @Override
6879 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6880 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6881 int wakefulness) {
6882 synchronized (mGlobalLock) {
6883 if (mHomeProcess != null && (dumpPackage == null
6884 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6885 if (needSep) {
6886 pw.println();
6887 needSep = false;
6888 }
6889 pw.println(" mHomeProcess: " + mHomeProcess);
6890 }
6891 if (mPreviousProcess != null && (dumpPackage == null
6892 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6893 if (needSep) {
6894 pw.println();
6895 needSep = false;
6896 }
6897 pw.println(" mPreviousProcess: " + mPreviousProcess);
6898 }
6899 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6900 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6901 StringBuilder sb = new StringBuilder(128);
6902 sb.append(" mPreviousProcessVisibleTime: ");
6903 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6904 pw.println(sb);
6905 }
6906 if (mHeavyWeightProcess != null && (dumpPackage == null
6907 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6908 if (needSep) {
6909 pw.println();
6910 needSep = false;
6911 }
6912 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6913 }
6914 if (dumpPackage == null) {
6915 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006916 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006917 }
6918 if (dumpAll) {
6919 if (dumpPackage == null) {
6920 pw.println(" mConfigWillChange: "
6921 + getTopDisplayFocusedStack().mConfigWillChange);
6922 }
6923 if (mCompatModePackages.getPackages().size() > 0) {
6924 boolean printed = false;
6925 for (Map.Entry<String, Integer> entry
6926 : mCompatModePackages.getPackages().entrySet()) {
6927 String pkg = entry.getKey();
6928 int mode = entry.getValue();
6929 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6930 continue;
6931 }
6932 if (!printed) {
6933 pw.println(" mScreenCompatPackages:");
6934 printed = true;
6935 }
6936 pw.println(" " + pkg + ": " + mode);
6937 }
6938 }
6939 }
6940
6941 if (dumpPackage == null) {
6942 pw.println(" mWakefulness="
6943 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006944 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006945 if (mRunningVoice != null) {
6946 pw.println(" mRunningVoice=" + mRunningVoice);
6947 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6948 }
6949 pw.println(" mSleeping=" + mSleeping);
6950 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6951 pw.println(" mVrController=" + mVrController);
6952 }
6953 if (mCurAppTimeTracker != null) {
6954 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6955 }
6956 if (mAllowAppSwitchUids.size() > 0) {
6957 boolean printed = false;
6958 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6959 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6960 for (int j = 0; j < types.size(); j++) {
6961 if (dumpPackage == null ||
6962 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6963 if (needSep) {
6964 pw.println();
6965 needSep = false;
6966 }
6967 if (!printed) {
6968 pw.println(" mAllowAppSwitchUids:");
6969 printed = true;
6970 }
6971 pw.print(" User ");
6972 pw.print(mAllowAppSwitchUids.keyAt(i));
6973 pw.print(": Type ");
6974 pw.print(types.keyAt(j));
6975 pw.print(" = ");
6976 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6977 pw.println();
6978 }
6979 }
6980 }
6981 }
6982 if (dumpPackage == null) {
6983 if (mController != null) {
6984 pw.println(" mController=" + mController
6985 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6986 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006987 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6988 pw.println(" mLaunchingActivityWakeLock="
6989 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006990 }
6991
6992 return needSep;
6993 }
6994 }
6995
6996 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006997 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6998 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006999 synchronized (mGlobalLock) {
7000 if (dumpPackage == null) {
7001 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7002 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007003 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7004 if (mRunningVoice != null) {
7005 final long vrToken = proto.start(
7006 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7007 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7008 mRunningVoice.toString());
7009 mVoiceWakeLock.writeToProto(
7010 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7011 proto.end(vrToken);
7012 }
7013 mVrController.writeToProto(proto,
7014 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007015 if (mController != null) {
7016 final long token = proto.start(CONTROLLER);
7017 proto.write(CONTROLLER, mController.toString());
7018 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7019 proto.end(token);
7020 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007021 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7022 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7023 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007024 }
7025
7026 if (mHomeProcess != null && (dumpPackage == null
7027 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007028 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007029 }
7030
7031 if (mPreviousProcess != null && (dumpPackage == null
7032 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007033 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007034 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7035 }
7036
7037 if (mHeavyWeightProcess != null && (dumpPackage == null
7038 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007039 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007040 }
7041
7042 for (Map.Entry<String, Integer> entry
7043 : mCompatModePackages.getPackages().entrySet()) {
7044 String pkg = entry.getKey();
7045 int mode = entry.getValue();
7046 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7047 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7048 proto.write(PACKAGE, pkg);
7049 proto.write(MODE, mode);
7050 proto.end(compatToken);
7051 }
7052 }
7053
7054 if (mCurAppTimeTracker != null) {
7055 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7056 }
7057
7058 }
7059 }
7060
7061 @Override
7062 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7063 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7064 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007065 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7066 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007067 }
7068
7069 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007070 public void dumpForOom(PrintWriter pw) {
7071 synchronized (mGlobalLock) {
7072 pw.println(" mHomeProcess: " + mHomeProcess);
7073 pw.println(" mPreviousProcess: " + mPreviousProcess);
7074 if (mHeavyWeightProcess != null) {
7075 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7076 }
7077 }
7078 }
7079
7080 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007081 public boolean canGcNow() {
7082 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007083 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 }
7085 }
7086
Riddle Hsua0536432019-02-16 00:38:59 +08007087 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 @Override
7089 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007090 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007091 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007092 return top != null ? top.app : null;
7093 }
7094 }
7095
Riddle Hsua0536432019-02-16 00:38:59 +08007096 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007097 @Override
7098 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007099 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007100 if (mRootActivityContainer != null) {
7101 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 }
7103 }
7104 }
7105
7106 @Override
7107 public void scheduleDestroyAllActivities(String reason) {
7108 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007109 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007110 }
7111 }
7112
7113 @Override
7114 public void removeUser(int userId) {
7115 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007116 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007117 }
7118 }
7119
7120 @Override
7121 public boolean switchUser(int userId, UserState userState) {
7122 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007123 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 }
7125 }
7126
7127 @Override
7128 public void onHandleAppCrash(WindowProcessController wpc) {
7129 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007130 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 }
7132 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007133
7134 @Override
7135 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7136 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007137 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007138 }
7139 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007140
Riddle Hsua0536432019-02-16 00:38:59 +08007141 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007142 @Override
7143 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007144 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007145 }
7146
Riddle Hsua0536432019-02-16 00:38:59 +08007147 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007148 @Override
7149 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007150 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007151 }
7152
Riddle Hsua0536432019-02-16 00:38:59 +08007153 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007154 @Override
7155 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007156 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007157 }
7158
Riddle Hsua0536432019-02-16 00:38:59 +08007159 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007160 @Override
7161 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007162 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007163 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007164
7165 @Override
7166 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007167 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007168 mPendingTempWhitelist.put(uid, tag);
7169 }
7170 }
7171
7172 @Override
7173 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007174 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007175 mPendingTempWhitelist.remove(uid);
7176 }
7177 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007178
7179 @Override
7180 public boolean handleAppCrashInActivityController(String processName, int pid,
7181 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7182 Runnable killCrashingAppCallback) {
7183 synchronized (mGlobalLock) {
7184 if (mController == null) {
7185 return false;
7186 }
7187
7188 try {
7189 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7190 stackTrace)) {
7191 killCrashingAppCallback.run();
7192 return true;
7193 }
7194 } catch (RemoteException e) {
7195 mController = null;
7196 Watchdog.getInstance().setActivityController(null);
7197 }
7198 return false;
7199 }
7200 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007201
7202 @Override
7203 public void removeRecentTasksByPackageName(String packageName, int userId) {
7204 synchronized (mGlobalLock) {
7205 mRecentTasks.removeTasksByPackageName(packageName, userId);
7206 }
7207 }
7208
7209 @Override
7210 public void cleanupRecentTasksForUser(int userId) {
7211 synchronized (mGlobalLock) {
7212 mRecentTasks.cleanupLocked(userId);
7213 }
7214 }
7215
7216 @Override
7217 public void loadRecentTasksForUser(int userId) {
7218 synchronized (mGlobalLock) {
7219 mRecentTasks.loadUserRecentsLocked(userId);
7220 }
7221 }
7222
7223 @Override
7224 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7225 synchronized (mGlobalLock) {
7226 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7227 }
7228 }
7229
7230 @Override
7231 public void flushRecentTasks() {
7232 mRecentTasks.flush();
7233 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007234
7235 @Override
7236 public WindowProcessController getHomeProcess() {
7237 synchronized (mGlobalLock) {
7238 return mHomeProcess;
7239 }
7240 }
7241
7242 @Override
7243 public WindowProcessController getPreviousProcess() {
7244 synchronized (mGlobalLock) {
7245 return mPreviousProcess;
7246 }
7247 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007248
7249 @Override
7250 public void clearLockedTasks(String reason) {
7251 synchronized (mGlobalLock) {
7252 getLockTaskController().clearLockedTasks(reason);
7253 }
7254 }
7255
7256 @Override
7257 public void updateUserConfiguration() {
7258 synchronized (mGlobalLock) {
7259 final Configuration configuration = new Configuration(getGlobalConfiguration());
7260 final int currentUserId = mAmInternal.getCurrentUserId();
7261 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7262 configuration, currentUserId, Settings.System.canWrite(mContext));
7263 updateConfigurationLocked(configuration, null /* starting */,
7264 false /* initLocale */, false /* persistent */, currentUserId,
7265 false /* deferResume */);
7266 }
7267 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007268
7269 @Override
7270 public boolean canShowErrorDialogs() {
7271 synchronized (mGlobalLock) {
7272 return mShowDialogs && !mSleeping && !mShuttingDown
7273 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7274 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7275 mAmInternal.getCurrentUserId())
7276 && !(UserManager.isDeviceInDemoMode(mContext)
7277 && mAmInternal.getCurrentUser().isDemo());
7278 }
7279 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007280
7281 @Override
7282 public void setProfileApp(String profileApp) {
7283 synchronized (mGlobalLock) {
7284 mProfileApp = profileApp;
7285 }
7286 }
7287
7288 @Override
7289 public void setProfileProc(WindowProcessController wpc) {
7290 synchronized (mGlobalLock) {
7291 mProfileProc = wpc;
7292 }
7293 }
7294
7295 @Override
7296 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7297 synchronized (mGlobalLock) {
7298 mProfilerInfo = profilerInfo;
7299 }
7300 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007301
7302 @Override
7303 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7304 synchronized (mGlobalLock) {
7305 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7306 }
7307 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007308
7309 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007310 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7311 boolean reducedResolution) {
7312 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7313 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007314 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007315
7316 @Override
7317 public boolean isUidForeground(int uid) {
7318 synchronized (mGlobalLock) {
7319 return ActivityTaskManagerService.this.isUidForeground(uid);
7320 }
7321 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007322
7323 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007324 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007325 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007326 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007327 }
7328 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007329
7330 @Override
7331 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007332 // Translate package names into UIDs
7333 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007334 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007335 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7336 if (uid >= 0) {
7337 result.add(uid);
7338 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007339 }
7340 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007341 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007342 }
7343 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007344 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007345}