blob: 7267da0da4ae2bd25d6e6e5c607c25f53ab8a622 [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;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
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 /**
364 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
365 * 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;
Garfield Tane0846042018-07-26 13:42:04 -0700733 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734
735 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900736 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737
738 final Configuration configuration = new Configuration();
739 Settings.System.getConfiguration(resolver, configuration);
740 if (forceRtl) {
741 // This will take care of setting the correct layout direction flags
742 configuration.setLayoutDirection(configuration.locale);
743 }
744
745 synchronized (mGlobalLock) {
746 mForceResizableActivities = forceResizable;
747 final boolean multiWindowFormEnabled = freeformWindowManagement
748 || supportsSplitScreenMultiWindow
749 || supportsPictureInPicture
750 || supportsMultiDisplay;
751 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
752 mSupportsMultiWindow = true;
753 mSupportsFreeformWindowManagement = freeformWindowManagement;
754 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
755 mSupportsPictureInPicture = supportsPictureInPicture;
756 mSupportsMultiDisplay = supportsMultiDisplay;
757 } else {
758 mSupportsMultiWindow = false;
759 mSupportsFreeformWindowManagement = false;
760 mSupportsSplitScreenMultiWindow = false;
761 mSupportsPictureInPicture = false;
762 mSupportsMultiDisplay = false;
763 }
764 mWindowManager.setForceResizableTasks(mForceResizableActivities);
765 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700766 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
767 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700768 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769 // This happens before any activities are started, so we can change global configuration
770 // in-place.
771 updateConfigurationLocked(configuration, null, true);
772 final Configuration globalConfig = getGlobalConfiguration();
773 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
774
775 // Load resources only after the current configuration has been set.
776 final Resources res = mContext.getResources();
777 mThumbnailWidth = res.getDimensionPixelSize(
778 com.android.internal.R.dimen.thumbnail_width);
779 mThumbnailHeight = res.getDimensionPixelSize(
780 com.android.internal.R.dimen.thumbnail_height);
781
782 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
783 mFullscreenThumbnailScale = (float) res
784 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
785 (float) globalConfig.screenWidthDp;
786 } else {
787 mFullscreenThumbnailScale = res.getFraction(
788 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
789 }
790 }
791 }
792
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800793 public WindowManagerGlobalLock getGlobalLock() {
794 return mGlobalLock;
795 }
796
Yunfan Chen585f2932019-01-29 16:04:45 +0900797 /** For test purpose only. */
798 @VisibleForTesting
799 public ActivityTaskManagerInternal getAtmInternal() {
800 return mInternal;
801 }
802
Riddle Hsud93a6c42018-11-29 21:50:06 +0800803 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
804 Looper looper) {
805 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700808 final File systemDir = SystemServiceManager.ensureSystemDir();
809 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
810 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700812
813 mTempConfig.setToDefaults();
814 mTempConfig.setLocales(LocaleList.getDefault());
815 mConfigurationSeq = mTempConfig.seq = 1;
816 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800817 mRootActivityContainer = new RootActivityContainer(this);
818 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700822 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700824 mRecentTasks = createRecentTasks();
825 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mKeyguardController = mStackSupervisor.getKeyguardController();
828 }
829
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 public void onActivityManagerInternalAdded() {
831 synchronized (mGlobalLock) {
832 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
833 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
834 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700835 }
836
Yunfan Chen75157d72018-07-27 14:47:21 +0900837 int increaseConfigurationSeqLocked() {
838 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
839 return mConfigurationSeq;
840 }
841
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700842 protected ActivityStackSupervisor createStackSupervisor() {
843 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
844 supervisor.initialize();
845 return supervisor;
846 }
847
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 public void setWindowManager(WindowManagerService wm) {
849 synchronized (mGlobalLock) {
850 mWindowManager = wm;
851 mLockTaskController.setWindowManager(wm);
852 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800853 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700854 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700855 }
856
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700857 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
858 synchronized (mGlobalLock) {
859 mUsageStatsInternal = usageStatsManager;
860 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700861 }
862
Wale Ogunwalef6733932018-06-27 05:14:34 -0700863 UserManagerService getUserManager() {
864 if (mUserManager == null) {
865 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
866 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
867 }
868 return mUserManager;
869 }
870
871 AppOpsService getAppOpsService() {
872 if (mAppOpsService == null) {
873 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
874 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
875 }
876 return mAppOpsService;
877 }
878
879 boolean hasUserRestriction(String restriction, int userId) {
880 return getUserManager().hasUserRestriction(restriction, userId);
881 }
882
Michal Karpinski15486842019-04-25 17:33:42 +0100883 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
884 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
885 callingUid, callingPackage);
886 if (mode == AppOpsManager.MODE_DEFAULT) {
887 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
888 == PERMISSION_GRANTED;
889 }
890 return mode == AppOpsManager.MODE_ALLOWED;
891 }
892
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700893 protected RecentTasks createRecentTasks() {
894 return new RecentTasks(this, mStackSupervisor);
895 }
896
897 RecentTasks getRecentTasks() {
898 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700899 }
900
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700901 ClientLifecycleManager getLifecycleManager() {
902 return mLifecycleManager;
903 }
904
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700905 ActivityStartController getActivityStartController() {
906 return mActivityStartController;
907 }
908
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700909 TaskChangeNotificationController getTaskChangeNotificationController() {
910 return mTaskChangeNotificationController;
911 }
912
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700913 LockTaskController getLockTaskController() {
914 return mLockTaskController;
915 }
916
Yunfan Chen75157d72018-07-27 14:47:21 +0900917 /**
918 * Return the global configuration used by the process corresponding to the input pid. This is
919 * usually the global configuration with some overrides specific to that process.
920 */
921 Configuration getGlobalConfigurationForCallingPid() {
922 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800923 return getGlobalConfigurationForPid(pid);
924 }
925
926 /**
927 * Return the global configuration used by the process corresponding to the given pid.
928 */
929 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 if (pid == MY_PID || pid < 0) {
931 return getGlobalConfiguration();
932 }
933 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100934 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900935 return app != null ? app.getConfiguration() : getGlobalConfiguration();
936 }
937 }
938
939 /**
940 * Return the device configuration info used by the process corresponding to the input pid.
941 * The value is consistent with the global configuration for the process.
942 */
943 @Override
944 public ConfigurationInfo getDeviceConfigurationInfo() {
945 ConfigurationInfo config = new ConfigurationInfo();
946 synchronized (mGlobalLock) {
947 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
948 config.reqTouchScreen = globalConfig.touchscreen;
949 config.reqKeyboardType = globalConfig.keyboard;
950 config.reqNavigation = globalConfig.navigation;
951 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
952 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
954 }
955 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
956 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
957 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
958 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700959 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 }
961 return config;
962 }
963
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700964 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700965 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700966 }
967
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700968 public static final class Lifecycle extends SystemService {
969 private final ActivityTaskManagerService mService;
970
971 public Lifecycle(Context context) {
972 super(context);
973 mService = new ActivityTaskManagerService(context);
974 }
975
976 @Override
977 public void onStart() {
978 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700979 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 }
981
Garfield Tan891146c2018-10-09 12:14:00 -0700982 @Override
983 public void onUnlockUser(int userId) {
984 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800985 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700986 }
987 }
988
989 @Override
990 public void onCleanupUser(int userId) {
991 synchronized (mService.getGlobalLock()) {
992 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
993 }
994 }
995
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700996 public ActivityTaskManagerService getService() {
997 return mService;
998 }
999 }
1000
1001 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001002 public final int startActivity(IApplicationThread caller, String callingPackage,
1003 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1004 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1005 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1006 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1007 UserHandle.getCallingUserId());
1008 }
1009
1010 @Override
1011 public final int startActivities(IApplicationThread caller, String callingPackage,
1012 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1013 int userId) {
1014 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 enforceNotIsolatedCaller(reason);
1016 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001018 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1019 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1020 reason, null /* originatingPendingIntent */,
1021 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 }
1023
1024 @Override
1025 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1026 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1027 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1028 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1029 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1030 true /*validateIncomingUser*/);
1031 }
1032
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001033 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1035 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1036 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001039 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1041
1042 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001043 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 .setCaller(caller)
1045 .setCallingPackage(callingPackage)
1046 .setResolvedType(resolvedType)
1047 .setResultTo(resultTo)
1048 .setResultWho(resultWho)
1049 .setRequestCode(requestCode)
1050 .setStartFlags(startFlags)
1051 .setProfilerInfo(profilerInfo)
1052 .setActivityOptions(bOptions)
1053 .setMayWait(userId)
1054 .execute();
1055
1056 }
1057
1058 @Override
1059 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1060 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001061 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1062 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 // Refuse possible leaked file descriptors
1064 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1065 throw new IllegalArgumentException("File descriptors passed in Intent");
1066 }
1067
1068 if (!(target instanceof PendingIntentRecord)) {
1069 throw new IllegalArgumentException("Bad PendingIntent object");
1070 }
1071
1072 PendingIntentRecord pir = (PendingIntentRecord)target;
1073
1074 synchronized (mGlobalLock) {
1075 // If this is coming from the currently resumed activity, it is
1076 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001077 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 if (stack.mResumedActivity != null &&
1079 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001080 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 }
1082 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 }
1086
1087 @Override
1088 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1089 Bundle bOptions) {
1090 // Refuse possible leaked file descriptors
1091 if (intent != null && intent.hasFileDescriptors()) {
1092 throw new IllegalArgumentException("File descriptors passed in Intent");
1093 }
1094 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1095
1096 synchronized (mGlobalLock) {
1097 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1098 if (r == null) {
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001102 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 // The caller is not running... d'oh!
1104 SafeActivityOptions.abort(options);
1105 return false;
1106 }
1107 intent = new Intent(intent);
1108 // The caller is not allowed to change the data.
1109 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1110 // And we are resetting to find the next component...
1111 intent.setComponent(null);
1112
1113 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1114
1115 ActivityInfo aInfo = null;
1116 try {
1117 List<ResolveInfo> resolves =
1118 AppGlobals.getPackageManager().queryIntentActivities(
1119 intent, r.resolvedType,
1120 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1121 UserHandle.getCallingUserId()).getList();
1122
1123 // Look for the original activity in the list...
1124 final int N = resolves != null ? resolves.size() : 0;
1125 for (int i=0; i<N; i++) {
1126 ResolveInfo rInfo = resolves.get(i);
1127 if (rInfo.activityInfo.packageName.equals(r.packageName)
1128 && rInfo.activityInfo.name.equals(r.info.name)) {
1129 // We found the current one... the next matching is
1130 // after it.
1131 i++;
1132 if (i<N) {
1133 aInfo = resolves.get(i).activityInfo;
1134 }
1135 if (debug) {
1136 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1137 + "/" + r.info.name);
1138 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1139 ? "null" : aInfo.packageName + "/" + aInfo.name));
1140 }
1141 break;
1142 }
1143 }
1144 } catch (RemoteException e) {
1145 }
1146
1147 if (aInfo == null) {
1148 // Nobody who is next!
1149 SafeActivityOptions.abort(options);
1150 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1151 return false;
1152 }
1153
1154 intent.setComponent(new ComponentName(
1155 aInfo.applicationInfo.packageName, aInfo.name));
1156 intent.setFlags(intent.getFlags()&~(
1157 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1158 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1159 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1160 FLAG_ACTIVITY_NEW_TASK));
1161
1162 // Okay now we need to start the new activity, replacing the currently running activity.
1163 // This is a little tricky because we want to start the new one as if the current one is
1164 // finished, but not finish the current one first so that there is no flicker.
1165 // And thus...
1166 final boolean wasFinishing = r.finishing;
1167 r.finishing = true;
1168
1169 // Propagate reply information over to the new activity.
1170 final ActivityRecord resultTo = r.resultTo;
1171 final String resultWho = r.resultWho;
1172 final int requestCode = r.requestCode;
1173 r.resultTo = null;
1174 if (resultTo != null) {
1175 resultTo.removeResultsLocked(r, resultWho, requestCode);
1176 }
1177
1178 final long origId = Binder.clearCallingIdentity();
1179 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001180 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001181 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001182 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001183 .setResolvedType(r.resolvedType)
1184 .setActivityInfo(aInfo)
1185 .setResultTo(resultTo != null ? resultTo.appToken : null)
1186 .setResultWho(resultWho)
1187 .setRequestCode(requestCode)
1188 .setCallingPid(-1)
1189 .setCallingUid(r.launchedFromUid)
1190 .setCallingPackage(r.launchedFromPackage)
1191 .setRealCallingPid(-1)
1192 .setRealCallingUid(r.launchedFromUid)
1193 .setActivityOptions(options)
1194 .execute();
1195 Binder.restoreCallingIdentity(origId);
1196
1197 r.finishing = wasFinishing;
1198 if (res != ActivityManager.START_SUCCESS) {
1199 return false;
1200 }
1201 return true;
1202 }
1203 }
1204
1205 @Override
1206 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1207 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1208 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1209 final WaitResult res = new WaitResult();
1210 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001211 enforceNotIsolatedCaller("startActivityAndWait");
1212 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1213 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001214 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001215 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 .setCaller(caller)
1217 .setCallingPackage(callingPackage)
1218 .setResolvedType(resolvedType)
1219 .setResultTo(resultTo)
1220 .setResultWho(resultWho)
1221 .setRequestCode(requestCode)
1222 .setStartFlags(startFlags)
1223 .setActivityOptions(bOptions)
1224 .setMayWait(userId)
1225 .setProfilerInfo(profilerInfo)
1226 .setWaitResult(res)
1227 .execute();
1228 }
1229 return res;
1230 }
1231
1232 @Override
1233 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1235 int startFlags, Configuration config, Bundle bOptions, int userId) {
1236 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001237 enforceNotIsolatedCaller("startActivityWithConfig");
1238 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1239 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001240 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001241 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001242 .setCaller(caller)
1243 .setCallingPackage(callingPackage)
1244 .setResolvedType(resolvedType)
1245 .setResultTo(resultTo)
1246 .setResultWho(resultWho)
1247 .setRequestCode(requestCode)
1248 .setStartFlags(startFlags)
1249 .setGlobalConfiguration(config)
1250 .setActivityOptions(bOptions)
1251 .setMayWait(userId)
1252 .execute();
1253 }
1254 }
1255
Alison Cichowlas3e340502018-08-07 17:15:01 -04001256
1257 @Override
1258 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1259 int callingUid = Binder.getCallingUid();
1260 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1261 throw new SecurityException("Only the system process can request a permission token, "
1262 + "received request from uid: " + callingUid);
1263 }
1264 IBinder permissionToken = new Binder();
1265 synchronized (mGlobalLock) {
1266 mStartActivitySources.put(permissionToken, delegatorToken);
1267 }
1268
1269 Message expireMsg = PooledLambda.obtainMessage(
1270 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1271 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1272
1273 Message forgetMsg = PooledLambda.obtainMessage(
1274 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1275 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1276
1277 return permissionToken;
1278 }
1279
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 @Override
1281 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1282 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1284 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001286 // permission grants) as any app that may launch one of your own activities. So we only
1287 // allow this in two cases:
1288 // 1) The caller is an activity that is part of the core framework, and then only when it
1289 // is running as the system.
1290 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1291 // can only be requested by a system activity, which may then delegate this call to
1292 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 final ActivityRecord sourceRecord;
1294 final int targetUid;
1295 final String targetPackage;
1296 final boolean isResolver;
1297 synchronized (mGlobalLock) {
1298 if (resultTo == null) {
1299 throw new SecurityException("Must be called from an activity");
1300 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001301 final IBinder sourceToken;
1302 if (permissionToken != null) {
1303 // To even attempt to use a permissionToken, an app must also have this signature
1304 // permission.
1305 mAmInternal.enforceCallingPermission(
1306 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1307 "startActivityAsCaller");
1308 // If called with a permissionToken, we want the sourceRecord from the delegator
1309 // activity that requested this token.
1310 sourceToken = mStartActivitySources.remove(permissionToken);
1311 if (sourceToken == null) {
1312 // Invalid permissionToken, check if it recently expired.
1313 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1314 throw new SecurityException("Called with expired permission token: "
1315 + permissionToken);
1316 } else {
1317 throw new SecurityException("Called with invalid permission token: "
1318 + permissionToken);
1319 }
1320 }
1321 } else {
1322 // This method was called directly by the source.
1323 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325
Wale Ogunwaled32da472018-11-16 07:19:28 -08001326 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327 if (sourceRecord == null) {
1328 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 }
1330 if (sourceRecord.app == null) {
1331 throw new SecurityException("Called without a process attached to activity");
1332 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333
1334 // Whether called directly or from a delegate, the source activity must be from the
1335 // android package.
1336 if (!sourceRecord.info.packageName.equals("android")) {
1337 throw new SecurityException("Must be called from an activity that is "
1338 + "declared in the android package");
1339 }
1340
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 // This is still okay, as long as this activity is running under the
1343 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001344 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001346 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 + " must be system uid or original calling uid "
1348 + sourceRecord.launchedFromUid);
1349 }
1350 }
1351 if (ignoreTargetSecurity) {
1352 if (intent.getComponent() == null) {
1353 throw new SecurityException(
1354 "Component must be specified with ignoreTargetSecurity");
1355 }
1356 if (intent.getSelector() != null) {
1357 throw new SecurityException(
1358 "Selector not allowed with ignoreTargetSecurity");
1359 }
1360 }
1361 targetUid = sourceRecord.launchedFromUid;
1362 targetPackage = sourceRecord.launchedFromPackage;
1363 isResolver = sourceRecord.isResolverOrChildActivity();
1364 }
1365
1366 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001367 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 }
1369
1370 // TODO: Switch to user app stacks here.
1371 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001372 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 .setCallingUid(targetUid)
1374 .setCallingPackage(targetPackage)
1375 .setResolvedType(resolvedType)
1376 .setResultTo(resultTo)
1377 .setResultWho(resultWho)
1378 .setRequestCode(requestCode)
1379 .setStartFlags(startFlags)
1380 .setActivityOptions(bOptions)
1381 .setMayWait(userId)
1382 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1383 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001384 // The target may well be in the background, which would normally prevent it
1385 // from starting an activity. Here we definitely want the start to succeed.
1386 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 .execute();
1388 } catch (SecurityException e) {
1389 // XXX need to figure out how to propagate to original app.
1390 // A SecurityException here is generally actually a fault of the original
1391 // calling activity (such as a fairly granting permissions), so propagate it
1392 // back to them.
1393 /*
1394 StringBuilder msg = new StringBuilder();
1395 msg.append("While launching");
1396 msg.append(intent.toString());
1397 msg.append(": ");
1398 msg.append(e.getMessage());
1399 */
1400 throw e;
1401 }
1402 }
1403
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001404 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1405 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1406 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1407 }
1408
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 @Override
1410 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1411 Intent intent, String resolvedType, IVoiceInteractionSession session,
1412 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1413 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001414 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 if (session == null || interactor == null) {
1416 throw new NullPointerException("null session or interactor");
1417 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001420 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 .setCallingUid(callingUid)
1422 .setCallingPackage(callingPackage)
1423 .setResolvedType(resolvedType)
1424 .setVoiceSession(session)
1425 .setVoiceInteractor(interactor)
1426 .setStartFlags(startFlags)
1427 .setProfilerInfo(profilerInfo)
1428 .setActivityOptions(bOptions)
1429 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001430 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 .execute();
1432 }
1433
1434 @Override
1435 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1436 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1438 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001440 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 .setCallingUid(callingUid)
1442 .setCallingPackage(callingPackage)
1443 .setResolvedType(resolvedType)
1444 .setActivityOptions(bOptions)
1445 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001446 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .execute();
1448 }
1449
Riddle Hsu609a8e22019-06-27 16:46:29 -06001450 /**
1451 * Start the recents activity to perform the recents animation.
1452 *
1453 * @param intent The intent to start the recents activity.
1454 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1455 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001457 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1458 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001459 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001461 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 final long origId = Binder.clearCallingIdentity();
1463 try {
1464 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001465 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1466 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001467 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001468
1469 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001470 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001471 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001472 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001473 if (recentsAnimationRunner == null) {
1474 anim.preloadRecentsActivity();
1475 } else {
1476 anim.startRecentsActivity(recentsAnimationRunner);
1477 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001478 }
1479 } finally {
1480 Binder.restoreCallingIdentity(origId);
1481 }
1482 }
1483
1484 @Override
1485 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001486 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001487 "startActivityFromRecents()");
1488
1489 final int callingPid = Binder.getCallingPid();
1490 final int callingUid = Binder.getCallingUid();
1491 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1492 final long origId = Binder.clearCallingIdentity();
1493 try {
1494 synchronized (mGlobalLock) {
1495 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1496 safeOptions);
1497 }
1498 } finally {
1499 Binder.restoreCallingIdentity(origId);
1500 }
1501 }
1502
1503 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001504 * Public API to check if the client is allowed to start an activity on specified display.
1505 *
1506 * If the target display is private or virtual, some restrictions will apply.
1507 *
1508 * @param displayId Target display id.
1509 * @param intent Intent used to launch the activity.
1510 * @param resolvedType The MIME type of the intent.
1511 * @param userId The id of the user for whom the call is made.
1512 * @return {@code true} if a call to start an activity on the target display should succeed and
1513 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1514 */
1515 @Override
1516 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1517 String resolvedType, int userId) {
1518 final int callingUid = Binder.getCallingUid();
1519 final int callingPid = Binder.getCallingPid();
1520 final long origId = Binder.clearCallingIdentity();
1521
1522 try {
1523 // Collect information about the target of the Intent.
1524 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1525 0 /* startFlags */, null /* profilerInfo */, userId,
1526 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1527 UserHandle.USER_NULL));
1528 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1529
1530 synchronized (mGlobalLock) {
1531 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1532 aInfo);
1533 }
1534 } finally {
1535 Binder.restoreCallingIdentity(origId);
1536 }
1537 }
1538
1539 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001540 * This is the internal entry point for handling Activity.finish().
1541 *
1542 * @param token The Binder token referencing the Activity we want to finish.
1543 * @param resultCode Result code, if any, from this Activity.
1544 * @param resultData Result data (Intent), if any, from this Activity.
1545 * @param finishTask Whether to finish the task associated with this Activity.
1546 *
1547 * @return Returns true if the activity successfully finished, or false if it is still running.
1548 */
1549 @Override
1550 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1551 int finishTask) {
1552 // Refuse possible leaked file descriptors
1553 if (resultData != null && resultData.hasFileDescriptors()) {
1554 throw new IllegalArgumentException("File descriptors passed in Intent");
1555 }
1556
1557 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001558 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001559 if (r == null) {
1560 return true;
1561 }
1562 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001563 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001564 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 if (rootR == null) {
1566 Slog.w(TAG, "Finishing task with all activities already finished");
1567 }
1568 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1569 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001570 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001571 return false;
1572 }
1573
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001574 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1575 // We should consolidate.
1576 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001578 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 if (next != null) {
1580 // ask watcher if this is allowed
1581 boolean resumeOK = true;
1582 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001583 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001585 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001586 Watchdog.getInstance().setActivityController(null);
1587 }
1588
1589 if (!resumeOK) {
1590 Slog.i(TAG, "Not finishing activity because controller resumed");
1591 return false;
1592 }
1593 }
1594 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001595
1596 // note down that the process has finished an activity and is in background activity
1597 // starts grace period
1598 if (r.app != null) {
1599 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1600 }
1601
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001602 final long origId = Binder.clearCallingIdentity();
1603 try {
1604 boolean res;
1605 final boolean finishWithRootActivity =
1606 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1607 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1608 || (finishWithRootActivity && r == rootR)) {
1609 // If requested, remove the task that is associated to this activity only if it
1610 // was the root activity in the task. The result code and data is ignored
1611 // because we don't support returning them across task boundaries. Also, to
1612 // keep backwards compatibility we remove the task from recents when finishing
1613 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001614 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001615 finishWithRootActivity, "finish-activity");
1616 if (!res) {
1617 Slog.i(TAG, "Removing task failed to finish activity");
1618 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001619 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001620 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001621 } else {
Andrii Kulian40eda672019-07-30 15:05:57 -07001622 r.finishActivityLocked(resultCode, resultData, "app-request",
1623 true /* oomAdj */);
1624 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 if (!res) {
1626 Slog.i(TAG, "Failed to finish by app-request");
1627 }
1628 }
1629 return res;
1630 } finally {
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633 }
1634 }
1635
1636 @Override
1637 public boolean finishActivityAffinity(IBinder token) {
1638 synchronized (mGlobalLock) {
1639 final long origId = Binder.clearCallingIdentity();
1640 try {
1641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1642 if (r == null) {
1643 return false;
1644 }
1645
1646 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1647 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001648 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001649 return false;
1650 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001651 r.finishActivityAffinity();
1652 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 } finally {
1654 Binder.restoreCallingIdentity(origId);
1655 }
1656 }
1657 }
1658
1659 @Override
1660 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1661 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001662 try {
1663 WindowProcessController proc = null;
1664 synchronized (mGlobalLock) {
1665 ActivityStack stack = ActivityRecord.getStackLocked(token);
1666 if (stack == null) {
1667 return;
1668 }
1669 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1670 false /* fromTimeout */, false /* processPausingActivities */, config);
1671 if (r != null) {
1672 proc = r.app;
1673 }
1674 if (stopProfiling && proc != null) {
1675 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001678 } finally {
1679 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001680 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 }
1682
1683 @Override
1684 public final void activityResumed(IBinder token) {
1685 final long origId = Binder.clearCallingIdentity();
1686 synchronized (mGlobalLock) {
1687 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001688 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001694 public final void activityTopResumedStateLost() {
1695 final long origId = Binder.clearCallingIdentity();
1696 synchronized (mGlobalLock) {
1697 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1698 }
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701
1702 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 public final void activityPaused(IBinder token) {
1704 final long origId = Binder.clearCallingIdentity();
1705 synchronized (mGlobalLock) {
1706 ActivityStack stack = ActivityRecord.getStackLocked(token);
1707 if (stack != null) {
1708 stack.activityPausedLocked(token, false);
1709 }
1710 }
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713
1714 @Override
1715 public final void activityStopped(IBinder token, Bundle icicle,
1716 PersistableBundle persistentState, CharSequence description) {
1717 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1718
1719 // Refuse possible leaked file descriptors
1720 if (icicle != null && icicle.hasFileDescriptors()) {
1721 throw new IllegalArgumentException("File descriptors passed in Bundle");
1722 }
1723
1724 final long origId = Binder.clearCallingIdentity();
1725
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001726 String restartingName = null;
1727 int restartingUid = 0;
1728 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001732 if (r.attachedToProcess()
1733 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1734 // The activity was requested to restart from
1735 // {@link #restartActivityProcessIfVisible}.
1736 restartingName = r.app.mName;
1737 restartingUid = r.app.mUid;
1738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 r.activityStoppedLocked(icicle, persistentState, description);
1740 }
1741 }
1742
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 if (restartingName != null) {
1744 // In order to let the foreground activity can be restarted with its saved state from
1745 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1746 // until the activity reports stopped with the state. And the activity record will be
1747 // kept because the record state is restarting, then the activity will be restarted
1748 // immediately if it is still the top one.
1749 mStackSupervisor.removeRestartTimeouts(r);
1750 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1751 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753
1754 Binder.restoreCallingIdentity(origId);
1755 }
1756
1757 @Override
1758 public final void activityDestroyed(IBinder token) {
1759 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1760 synchronized (mGlobalLock) {
1761 ActivityStack stack = ActivityRecord.getStackLocked(token);
1762 if (stack != null) {
1763 stack.activityDestroyedLocked(token, "activityDestroyed");
1764 }
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 }
1957 final boolean translucentChanged = r.changeWindowTranslucency(true);
1958 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001959 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 return translucentChanged;
1963 }
1964 } finally {
1965 Binder.restoreCallingIdentity(origId);
1966 }
1967 }
1968
1969 @Override
1970 public boolean convertToTranslucent(IBinder token, Bundle options) {
1971 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1972 final long origId = Binder.clearCallingIdentity();
1973 try {
1974 synchronized (mGlobalLock) {
1975 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1976 if (r == null) {
1977 return false;
1978 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001979 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 int index = task.mActivities.lastIndexOf(r);
1981 if (index > 0) {
1982 ActivityRecord under = task.mActivities.get(index - 1);
1983 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1984 }
1985 final boolean translucentChanged = r.changeWindowTranslucency(false);
1986 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001987 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001989 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001990 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 return translucentChanged;
1992 }
1993 } finally {
1994 Binder.restoreCallingIdentity(origId);
1995 }
1996 }
1997
1998 @Override
1999 public void notifyActivityDrawn(IBinder token) {
2000 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2001 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002002 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002004 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 }
2007 }
2008
2009 @Override
2010 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2011 synchronized (mGlobalLock) {
2012 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2013 if (r == null) {
2014 return;
2015 }
2016 r.reportFullyDrawnLocked(restoredFromBundle);
2017 }
2018 }
2019
2020 @Override
2021 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2022 synchronized (mGlobalLock) {
2023 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2024 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2025 return stack.mDisplayId;
2026 }
2027 return DEFAULT_DISPLAY;
2028 }
2029 }
2030
2031 @Override
2032 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 long ident = Binder.clearCallingIdentity();
2035 try {
2036 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002037 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002039 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return null;
2042 }
2043 } finally {
2044 Binder.restoreCallingIdentity(ident);
2045 }
2046 }
2047
2048 @Override
2049 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002050 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2052 final long callingId = Binder.clearCallingIdentity();
2053 try {
2054 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002055 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 if (stack == null) {
2057 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2058 return;
2059 }
2060 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002061 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002062 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(callingId);
2067 }
2068 }
2069
2070 @Override
2071 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2074 final long callingId = Binder.clearCallingIdentity();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002078 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (task == null) {
2080 return;
2081 }
2082 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002083 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002084 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 }
2087 } finally {
2088 Binder.restoreCallingIdentity(callingId);
2089 }
2090 }
2091
2092 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002093 public void restartActivityProcessIfVisible(IBinder activityToken) {
2094 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2095 final long callingId = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (mGlobalLock) {
2098 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2099 if (r == null) {
2100 return;
2101 }
2102 r.restartProcessIfVisible();
2103 }
2104 } finally {
2105 Binder.restoreCallingIdentity(callingId);
2106 }
2107 }
2108
2109 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002111 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 synchronized (mGlobalLock) {
2113 final long ident = Binder.clearCallingIdentity();
2114 try {
2115 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2116 "remove-task");
2117 } finally {
2118 Binder.restoreCallingIdentity(ident);
2119 }
2120 }
2121 }
2122
2123 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002124 public void removeAllVisibleRecentTasks() {
2125 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2126 synchronized (mGlobalLock) {
2127 final long ident = Binder.clearCallingIdentity();
2128 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002129 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002130 } finally {
2131 Binder.restoreCallingIdentity(ident);
2132 }
2133 }
2134 }
2135
2136 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2138 synchronized (mGlobalLock) {
2139 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2140 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002141 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 }
2143 }
2144 return false;
2145 }
2146
2147 @Override
2148 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2149 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002150
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002151 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002152 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2153 if (r != null) {
2154 return r.getActivityStack().navigateUpToLocked(
2155 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002156 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002157 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 }
2159 }
2160
2161 /**
2162 * Attempts to move a task backwards in z-order (the order of activities within the task is
2163 * unchanged).
2164 *
2165 * There are several possible results of this call:
2166 * - if the task is locked, then we will show the lock toast
2167 * - if there is a task behind the provided task, then that task is made visible and resumed as
2168 * this task is moved to the back
2169 * - otherwise, if there are no other tasks in the stack:
2170 * - if this task is in the pinned stack, then we remove the stack completely, which will
2171 * have the effect of moving the task to the top or bottom of the fullscreen stack
2172 * (depending on whether it is visible)
2173 * - otherwise, we simply return home and hide this task
2174 *
2175 * @param token A reference to the activity we wish to move
2176 * @param nonRoot If false then this only works if the activity is the root
2177 * of a task; if true it will work for any activity in a task.
2178 * @return Returns true if the move completed, false if not.
2179 */
2180 @Override
2181 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002182 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002183 synchronized (mGlobalLock) {
2184 final long origId = Binder.clearCallingIdentity();
2185 try {
2186 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002187 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 if (task != null) {
2189 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2190 }
2191 } finally {
2192 Binder.restoreCallingIdentity(origId);
2193 }
2194 }
2195 return false;
2196 }
2197
2198 @Override
2199 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002201 long ident = Binder.clearCallingIdentity();
2202 Rect rect = new Rect();
2203 try {
2204 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002205 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002206 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2207 if (task == null) {
2208 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2209 return rect;
2210 }
2211 if (task.getStack() != null) {
2212 // Return the bounds from window manager since it will be adjusted for various
2213 // things like the presense of a docked stack for tasks that aren't resizeable.
2214 task.getWindowContainerBounds(rect);
2215 } else {
2216 // Task isn't in window manager yet since it isn't associated with a stack.
2217 // Return the persist value from activity manager
2218 if (!task.matchParentBounds()) {
2219 rect.set(task.getBounds());
2220 } else if (task.mLastNonFullscreenBounds != null) {
2221 rect.set(task.mLastNonFullscreenBounds);
2222 }
2223 }
2224 }
2225 } finally {
2226 Binder.restoreCallingIdentity(ident);
2227 }
2228 return rect;
2229 }
2230
2231 @Override
2232 public ActivityManager.TaskDescription getTaskDescription(int id) {
2233 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002234 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002235 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002236 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002237 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2238 if (tr != null) {
2239 return tr.lastTaskDescription;
2240 }
2241 }
2242 return null;
2243 }
2244
2245 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002246 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2247 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2248 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2249 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2250 return;
2251 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002252 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002253 synchronized (mGlobalLock) {
2254 final long ident = Binder.clearCallingIdentity();
2255 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002256 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002257 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002258 if (task == null) {
2259 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2260 return;
2261 }
2262
2263 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2264 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2265
2266 if (!task.isActivityTypeStandardOrUndefined()) {
2267 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2268 + " non-standard task " + taskId + " to windowing mode="
2269 + windowingMode);
2270 }
2271
2272 final ActivityStack stack = task.getStack();
2273 if (toTop) {
2274 stack.moveToFront("setTaskWindowingMode", task);
2275 }
2276 stack.setWindowingMode(windowingMode);
2277 } finally {
2278 Binder.restoreCallingIdentity(ident);
2279 }
2280 }
2281 }
2282
2283 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002284 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002286 ActivityRecord r = getCallingRecordLocked(token);
2287 return r != null ? r.info.packageName : null;
2288 }
2289 }
2290
2291 @Override
2292 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002293 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 ActivityRecord r = getCallingRecordLocked(token);
2295 return r != null ? r.intent.getComponent() : null;
2296 }
2297 }
2298
2299 private ActivityRecord getCallingRecordLocked(IBinder token) {
2300 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2301 if (r == null) {
2302 return null;
2303 }
2304 return r.resultTo;
2305 }
2306
2307 @Override
2308 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002309 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310
2311 synchronized (mGlobalLock) {
2312 final long origId = Binder.clearCallingIdentity();
2313 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002314 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002315 } finally {
2316 Binder.restoreCallingIdentity(origId);
2317 }
2318 }
2319 }
2320
Mark Renouf446251d2019-04-26 10:22:41 -04002321 @Override
2322 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2323 synchronized (mGlobalLock) {
2324 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2325 if (r == null) {
2326 return;
2327 }
2328 ActivityStack stack = r.getActivityStack();
2329 if (stack != null && stack.isSingleTaskInstance()) {
2330 // Single-task stacks are used for activities which are presented in floating
2331 // windows above full screen activities. Instead of directly finishing the
2332 // task, a task change listener is used to notify SystemUI so the action can be
2333 // handled specially.
2334 final TaskRecord task = r.getTaskRecord();
2335 mTaskChangeNotificationController
2336 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2337 } else {
2338 try {
2339 callback.requestFinish();
2340 } catch (RemoteException e) {
2341 Slog.e(TAG, "Failed to invoke request finish callback", e);
2342 }
2343 }
2344 }
2345 }
2346
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002347 /**
2348 * TODO: Add mController hook
2349 */
2350 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002351 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2352 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002353 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354
2355 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2356 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2358 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002359 }
2360 }
2361
Ricky Waiaca8a772019-04-04 16:01:06 +01002362 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2363 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002364 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002365
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 final int callingPid = Binder.getCallingPid();
2367 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002368 if (!isSameApp(callingUid, callingPackage)) {
2369 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2370 + Binder.getCallingPid() + " as package " + callingPackage;
2371 Slog.w(TAG, msg);
2372 throw new SecurityException(msg);
2373 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002374 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002375 SafeActivityOptions.abort(options);
2376 return;
2377 }
2378 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 WindowProcessController callerApp = null;
2380 if (appThread != null) {
2381 callerApp = getProcessController(appThread);
2382 }
2383 final ActivityStarter starter = getActivityStartController().obtainStarter(
2384 null /* intent */, "moveTaskToFront");
2385 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2386 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002387 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 return;
2389 }
2390 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002392 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002393 if (task == null) {
2394 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002395 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002396 return;
2397 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002398 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002399 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002400 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002401 return;
2402 }
2403 ActivityOptions realOptions = options != null
2404 ? options.getOptions(mStackSupervisor)
2405 : null;
2406 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2407 false /* forceNonResizable */);
2408
2409 final ActivityRecord topActivity = task.getTopActivity();
2410 if (topActivity != null) {
2411
2412 // We are reshowing a task, use a starting window to hide the initial draw delay
2413 // so the transition can start earlier.
2414 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2415 true /* taskSwitch */, fromRecents);
2416 }
2417 } finally {
2418 Binder.restoreCallingIdentity(origId);
2419 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002420 }
2421
Ricky Waiaca8a772019-04-04 16:01:06 +01002422 /**
2423 * Return true if callingUid is system, or packageName belongs to that callingUid.
2424 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002425 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002426 try {
2427 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2428 if (packageName == null) {
2429 return false;
2430 }
2431 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2432 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2433 UserHandle.getUserId(callingUid));
2434 return UserHandle.isSameApp(callingUid, uid);
2435 }
2436 } catch (RemoteException e) {
2437 // Should not happen
2438 }
2439 return true;
2440 }
2441
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002442 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2443 int callingPid, int callingUid, String name) {
2444 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2445 return true;
2446 }
2447
2448 if (getRecentTasks().isCallerRecents(sourceUid)) {
2449 return true;
2450 }
2451
2452 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2453 if (perm == PackageManager.PERMISSION_GRANTED) {
2454 return true;
2455 }
2456 if (checkAllowAppSwitchUid(sourceUid)) {
2457 return true;
2458 }
2459
2460 // If the actual IPC caller is different from the logical source, then
2461 // also see if they are allowed to control app switches.
2462 if (callingUid != -1 && callingUid != sourceUid) {
2463 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2464 if (perm == PackageManager.PERMISSION_GRANTED) {
2465 return true;
2466 }
2467 if (checkAllowAppSwitchUid(callingUid)) {
2468 return true;
2469 }
2470 }
2471
2472 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2473 return false;
2474 }
2475
2476 private boolean checkAllowAppSwitchUid(int uid) {
2477 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2478 if (types != null) {
2479 for (int i = types.size() - 1; i >= 0; i--) {
2480 if (types.valueAt(i).intValue() == uid) {
2481 return true;
2482 }
2483 }
2484 }
2485 return false;
2486 }
2487
2488 @Override
2489 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2490 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2491 "setActivityController()");
2492 synchronized (mGlobalLock) {
2493 mController = controller;
2494 mControllerIsAMonkey = imAMonkey;
2495 Watchdog.getInstance().setActivityController(controller);
2496 }
2497 }
2498
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002499 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002500 synchronized (mGlobalLock) {
2501 return mController != null && mControllerIsAMonkey;
2502 }
2503 }
2504
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002505 @Override
2506 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2507 synchronized (mGlobalLock) {
2508 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2509 }
2510 }
2511
2512 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002513 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2514 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2515 }
2516
2517 @Override
2518 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2519 @WindowConfiguration.ActivityType int ignoreActivityType,
2520 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2521 final int callingUid = Binder.getCallingUid();
2522 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2523
2524 synchronized (mGlobalLock) {
2525 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2526
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002528 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002529 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002530 ignoreWindowingMode, callingUid, allowed);
2531 }
2532
2533 return list;
2534 }
2535
2536 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002537 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2538 synchronized (mGlobalLock) {
2539 final long origId = Binder.clearCallingIdentity();
2540 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2541 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002542 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002543 }
2544 Binder.restoreCallingIdentity(origId);
2545 }
2546 }
2547
2548 @Override
2549 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002550 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002551 ActivityStack stack = ActivityRecord.getStackLocked(token);
2552 if (stack != null) {
2553 return stack.willActivityBeVisibleLocked(token);
2554 }
2555 return false;
2556 }
2557 }
2558
2559 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002560 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002562 synchronized (mGlobalLock) {
2563 final long ident = Binder.clearCallingIdentity();
2564 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002565 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002566 if (task == null) {
2567 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2568 return;
2569 }
2570
2571 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2572 + " to stackId=" + stackId + " toTop=" + toTop);
2573
Wale Ogunwaled32da472018-11-16 07:19:28 -08002574 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002575 if (stack == null) {
2576 throw new IllegalStateException(
2577 "moveTaskToStack: No stack for stackId=" + stackId);
2578 }
2579 if (!stack.isActivityTypeStandardOrUndefined()) {
2580 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2581 + taskId + " to stack " + stackId);
2582 }
2583 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002584 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002585 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2586 }
2587 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2588 "moveTaskToStack");
2589 } finally {
2590 Binder.restoreCallingIdentity(ident);
2591 }
2592 }
2593 }
2594
2595 @Override
2596 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2597 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599
2600 final long ident = Binder.clearCallingIdentity();
2601 try {
2602 synchronized (mGlobalLock) {
2603 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002604 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 if (stack == null) {
2606 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2607 return;
2608 }
2609 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2610 throw new IllegalArgumentException("Stack: " + stackId
2611 + " doesn't support animated resize.");
2612 }
2613 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2614 animationDuration, false /* fromFullscreen */);
2615 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002616 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002617 if (stack == null) {
2618 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2619 return;
2620 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002621 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002622 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2623 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2624 }
2625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(ident);
2628 }
2629 }
2630
wilsonshih5c4cf522019-01-25 09:03:47 +08002631 @Override
2632 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2633 int animationDuration) {
2634 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2635
2636 final long ident = Binder.clearCallingIdentity();
2637 try {
2638 synchronized (mGlobalLock) {
2639 if (xOffset == 0 && yOffset == 0) {
2640 return;
2641 }
2642 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2643 if (stack == null) {
2644 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2645 return;
2646 }
2647 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2648 throw new IllegalArgumentException("Stack: " + stackId
2649 + " doesn't support animated resize.");
2650 }
2651 final Rect destBounds = new Rect();
2652 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002653 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002654 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2655 return;
2656 }
2657 destBounds.offset(xOffset, yOffset);
2658 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2659 animationDuration, false /* fromFullscreen */);
2660 }
2661 } finally {
2662 Binder.restoreCallingIdentity(ident);
2663 }
2664 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002665 /**
2666 * Moves the specified task to the primary-split-screen stack.
2667 *
2668 * @param taskId Id of task to move.
2669 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2670 * exist already. See
2671 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2672 * and
2673 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2674 * @param toTop If the task and stack should be moved to the top.
2675 * @param animate Whether we should play an animation for the moving the task.
2676 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2677 * stack. Pass {@code null} to use default bounds.
2678 * @param showRecents If the recents activity should be shown on the other side of the task
2679 * going into split-screen mode.
2680 */
2681 @Override
2682 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2683 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002684 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002685 "setTaskWindowingModeSplitScreenPrimary()");
2686 synchronized (mGlobalLock) {
2687 final long ident = Binder.clearCallingIdentity();
2688 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002689 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002690 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002691 if (task == null) {
2692 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2693 return false;
2694 }
2695 if (DEBUG_STACK) Slog.d(TAG_STACK,
2696 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2697 + " to createMode=" + createMode + " toTop=" + toTop);
2698 if (!task.isActivityTypeStandardOrUndefined()) {
2699 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2700 + " non-standard task " + taskId + " to split-screen windowing mode");
2701 }
2702
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002704 final int windowingMode = task.getWindowingMode();
2705 final ActivityStack stack = task.getStack();
2706 if (toTop) {
2707 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2708 }
2709 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002710 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2711 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002712 return windowingMode != task.getWindowingMode();
2713 } finally {
2714 Binder.restoreCallingIdentity(ident);
2715 }
2716 }
2717 }
2718
2719 /**
2720 * Removes stacks in the input windowing modes from the system if they are of activity type
2721 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2722 */
2723 @Override
2724 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002725 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002726 "removeStacksInWindowingModes()");
2727
2728 synchronized (mGlobalLock) {
2729 final long ident = Binder.clearCallingIdentity();
2730 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002731 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002732 } finally {
2733 Binder.restoreCallingIdentity(ident);
2734 }
2735 }
2736 }
2737
2738 @Override
2739 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002741 "removeStacksWithActivityTypes()");
2742
2743 synchronized (mGlobalLock) {
2744 final long ident = Binder.clearCallingIdentity();
2745 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002746 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002747 } finally {
2748 Binder.restoreCallingIdentity(ident);
2749 }
2750 }
2751 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752
2753 @Override
2754 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2755 int userId) {
2756 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002757 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2758 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002759 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 final boolean detailed = checkGetTasksPermission(
2761 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2762 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 == PackageManager.PERMISSION_GRANTED;
2764
2765 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002766 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 callingUid);
2768 }
2769 }
2770
2771 @Override
2772 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 long ident = Binder.clearCallingIdentity();
2775 try {
2776 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002777 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 }
2779 } finally {
2780 Binder.restoreCallingIdentity(ident);
2781 }
2782 }
2783
2784 @Override
2785 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002786 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 long ident = Binder.clearCallingIdentity();
2788 try {
2789 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002790 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002791 }
2792 } finally {
2793 Binder.restoreCallingIdentity(ident);
2794 }
2795 }
2796
2797 @Override
2798 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002799 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002800 final long callingUid = Binder.getCallingUid();
2801 final long origId = Binder.clearCallingIdentity();
2802 try {
2803 synchronized (mGlobalLock) {
2804 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002805 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002806 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2807 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2808 }
2809 } finally {
2810 Binder.restoreCallingIdentity(origId);
2811 }
2812 }
2813
2814 @Override
2815 public void startLockTaskModeByToken(IBinder token) {
2816 synchronized (mGlobalLock) {
2817 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2818 if (r == null) {
2819 return;
2820 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002821 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002822 }
2823 }
2824
2825 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002826 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002827 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002828 // This makes inner call to look as if it was initiated by system.
2829 long ident = Binder.clearCallingIdentity();
2830 try {
2831 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002832 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002833 MATCH_TASK_IN_STACKS_ONLY);
2834 if (task == null) {
2835 return;
2836 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837
2838 // When starting lock task mode the stack must be in front and focused
2839 task.getStack().moveToFront("startSystemLockTaskMode");
2840 startLockTaskModeLocked(task, true /* isSystemCaller */);
2841 }
2842 } finally {
2843 Binder.restoreCallingIdentity(ident);
2844 }
2845 }
2846
2847 @Override
2848 public void stopLockTaskModeByToken(IBinder token) {
2849 synchronized (mGlobalLock) {
2850 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2851 if (r == null) {
2852 return;
2853 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002854 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002855 }
2856 }
2857
2858 /**
2859 * This API should be called by SystemUI only when user perform certain action to dismiss
2860 * lock task mode. We should only dismiss pinned lock task mode in this case.
2861 */
2862 @Override
2863 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002864 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2866 }
2867
2868 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2869 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2870 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2871 return;
2872 }
2873
Wale Ogunwaled32da472018-11-16 07:19:28 -08002874 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002875 if (stack == null || task != stack.topTask()) {
2876 throw new IllegalArgumentException("Invalid task, not in foreground");
2877 }
2878
2879 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2880 // system or a specific app.
2881 // * System-initiated requests will only start the pinned mode (screen pinning)
2882 // * App-initiated requests
2883 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2884 // - will start the pinned mode, otherwise
2885 final int callingUid = Binder.getCallingUid();
2886 long ident = Binder.clearCallingIdentity();
2887 try {
2888 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002889 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002891 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 } finally {
2893 Binder.restoreCallingIdentity(ident);
2894 }
2895 }
2896
2897 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2898 final int callingUid = Binder.getCallingUid();
2899 long ident = Binder.clearCallingIdentity();
2900 try {
2901 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002902 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 }
2904 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2905 // task and jumping straight into a call in the case of emergency call back.
2906 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2907 if (tm != null) {
2908 tm.showInCallScreen(false);
2909 }
2910 } finally {
2911 Binder.restoreCallingIdentity(ident);
2912 }
2913 }
2914
2915 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002916 public void updateLockTaskPackages(int userId, String[] packages) {
2917 final int callingUid = Binder.getCallingUid();
2918 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2919 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2920 "updateLockTaskPackages()");
2921 }
2922 synchronized (this) {
2923 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2924 + Arrays.toString(packages));
2925 getLockTaskController().updateLockTaskPackages(userId, packages);
2926 }
2927 }
2928
2929 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 public boolean isInLockTaskMode() {
2931 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2932 }
2933
2934 @Override
2935 public int getLockTaskModeState() {
2936 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002937 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 }
2939 }
2940
2941 @Override
2942 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2943 synchronized (mGlobalLock) {
2944 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2945 if (r != null) {
2946 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002947 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002949 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 }
2951 }
2952 }
2953
2954 @Override
2955 public Bundle getActivityOptions(IBinder token) {
2956 final long origId = Binder.clearCallingIdentity();
2957 try {
2958 synchronized (mGlobalLock) {
2959 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2960 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002961 final ActivityOptions activityOptions = r.takeOptionsLocked(
2962 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002963 return activityOptions == null ? null : activityOptions.toBundle();
2964 }
2965 return null;
2966 }
2967 } finally {
2968 Binder.restoreCallingIdentity(origId);
2969 }
2970 }
2971
2972 @Override
2973 public List<IBinder> getAppTasks(String callingPackage) {
2974 int callingUid = Binder.getCallingUid();
2975 long ident = Binder.clearCallingIdentity();
2976 try {
2977 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002978 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 }
2980 } finally {
2981 Binder.restoreCallingIdentity(ident);
2982 }
2983 }
2984
2985 @Override
2986 public void finishVoiceTask(IVoiceInteractionSession session) {
2987 synchronized (mGlobalLock) {
2988 final long origId = Binder.clearCallingIdentity();
2989 try {
2990 // TODO: VI Consider treating local voice interactions and voice tasks
2991 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002992 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 } finally {
2994 Binder.restoreCallingIdentity(origId);
2995 }
2996 }
2997
2998 }
2999
3000 @Override
3001 public boolean isTopOfTask(IBinder token) {
3002 synchronized (mGlobalLock) {
3003 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003004 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003005 }
3006 }
3007
3008 @Override
3009 public void notifyLaunchTaskBehindComplete(IBinder token) {
3010 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3011 }
3012
3013 @Override
3014 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003015 mH.post(() -> {
3016 synchronized (mGlobalLock) {
3017 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003018 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003019 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003020 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003021 } catch (RemoteException e) {
3022 }
3023 }
3024 }
3025
3026 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003027 }
3028
3029 /** Called from an app when assist data is ready. */
3030 @Override
3031 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3032 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003033 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 synchronized (pae) {
3035 pae.result = extras;
3036 pae.structure = structure;
3037 pae.content = content;
3038 if (referrer != null) {
3039 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3040 }
3041 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003042 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003043 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3044 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 structure.setHomeActivity(pae.isHome);
3046 }
3047 pae.haveResult = true;
3048 pae.notifyAll();
3049 if (pae.intent == null && pae.receiver == null) {
3050 // Caller is just waiting for the result.
3051 return;
3052 }
3053 }
3054 // We are now ready to launch the assist activity.
3055 IAssistDataReceiver sendReceiver = null;
3056 Bundle sendBundle = null;
3057 synchronized (mGlobalLock) {
3058 buildAssistBundleLocked(pae, extras);
3059 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003060 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 if (!exists) {
3062 // Timed out.
3063 return;
3064 }
3065
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003066 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 // Caller wants result sent back to them.
3068 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003069 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3070 pae.activity.getTaskRecord().taskId);
3071 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3072 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3074 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3075 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3076 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3077 }
3078 }
3079 if (sendReceiver != null) {
3080 try {
3081 sendReceiver.onHandleAssistData(sendBundle);
3082 } catch (RemoteException e) {
3083 }
3084 return;
3085 }
3086
3087 final long ident = Binder.clearCallingIdentity();
3088 try {
3089 if (TextUtils.equals(pae.intent.getAction(),
3090 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003091 // Start voice interaction through VoiceInteractionManagerService.
3092 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3093 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003094 } else {
3095 pae.intent.replaceExtras(pae.extras);
3096 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3097 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3098 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003099 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003100
3101 try {
3102 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3103 } catch (ActivityNotFoundException e) {
3104 Slog.w(TAG, "No activity to handle assist action.", e);
3105 }
3106 }
3107 } finally {
3108 Binder.restoreCallingIdentity(ident);
3109 }
3110 }
3111
3112 @Override
3113 public int addAppTask(IBinder activityToken, Intent intent,
3114 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3115 final int callingUid = Binder.getCallingUid();
3116 final long callingIdent = Binder.clearCallingIdentity();
3117
3118 try {
3119 synchronized (mGlobalLock) {
3120 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3121 if (r == null) {
3122 throw new IllegalArgumentException("Activity does not exist; token="
3123 + activityToken);
3124 }
3125 ComponentName comp = intent.getComponent();
3126 if (comp == null) {
3127 throw new IllegalArgumentException("Intent " + intent
3128 + " must specify explicit component");
3129 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003130 if (thumbnail.getWidth() != mThumbnailWidth
3131 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003132 throw new IllegalArgumentException("Bad thumbnail size: got "
3133 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003134 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 }
3136 if (intent.getSelector() != null) {
3137 intent.setSelector(null);
3138 }
3139 if (intent.getSourceBounds() != null) {
3140 intent.setSourceBounds(null);
3141 }
3142 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3143 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3144 // The caller has added this as an auto-remove task... that makes no
3145 // sense, so turn off auto-remove.
3146 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3147 }
3148 }
3149 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3150 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3151 if (ainfo.applicationInfo.uid != callingUid) {
3152 throw new SecurityException(
3153 "Can't add task for another application: target uid="
3154 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3155 }
3156
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003157 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003159 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003160 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003161 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 // The app has too many tasks already and we can't add any more
3163 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3164 return INVALID_TASK_ID;
3165 }
3166 task.lastTaskDescription.copyFrom(description);
3167
3168 // TODO: Send the thumbnail to WM to store it.
3169
3170 return task.taskId;
3171 }
3172 } finally {
3173 Binder.restoreCallingIdentity(callingIdent);
3174 }
3175 }
3176
3177 @Override
3178 public Point getAppTaskThumbnailSize() {
3179 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003180 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003181 }
3182 }
3183
3184 @Override
3185 public void setTaskResizeable(int taskId, int resizeableMode) {
3186 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003187 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3189 if (task == null) {
3190 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3191 return;
3192 }
3193 task.setResizeMode(resizeableMode);
3194 }
3195 }
3196
3197 @Override
3198 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003199 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 long ident = Binder.clearCallingIdentity();
3201 try {
3202 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003203 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003204 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003205 if (task == null) {
3206 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3207 return;
3208 }
3209 // Place the task in the right stack if it isn't there already based on
3210 // the requested bounds.
3211 // The stack transition logic is:
3212 // - a null bounds on a freeform task moves that task to fullscreen
3213 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3214 // that task to freeform
3215 // - otherwise the task is not moved
3216 ActivityStack stack = task.getStack();
3217 if (!task.getWindowConfiguration().canResizeTask()) {
3218 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3219 }
3220 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3221 stack = stack.getDisplay().getOrCreateStack(
3222 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3223 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3224 stack = stack.getDisplay().getOrCreateStack(
3225 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3226 }
3227
3228 // Reparent the task to the right stack if necessary
3229 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3230 if (stack != task.getStack()) {
3231 // Defer resume until the task is resized below
3232 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3233 DEFER_RESUME, "resizeTask");
3234 preserveWindow = false;
3235 }
3236
3237 // After reparenting (which only resizes the task to the stack bounds), resize the
3238 // task to the actual bounds provided
3239 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3240 }
3241 } finally {
3242 Binder.restoreCallingIdentity(ident);
3243 }
3244 }
3245
3246 @Override
3247 public boolean releaseActivityInstance(IBinder token) {
3248 synchronized (mGlobalLock) {
3249 final long origId = Binder.clearCallingIdentity();
3250 try {
3251 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3252 if (r == null) {
3253 return false;
3254 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003255 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 } finally {
3257 Binder.restoreCallingIdentity(origId);
3258 }
3259 }
3260 }
3261
3262 @Override
3263 public void releaseSomeActivities(IApplicationThread appInt) {
3264 synchronized (mGlobalLock) {
3265 final long origId = Binder.clearCallingIdentity();
3266 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003267 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003268 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 } finally {
3270 Binder.restoreCallingIdentity(origId);
3271 }
3272 }
3273 }
3274
3275 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003276 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003277 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003278 != PackageManager.PERMISSION_GRANTED) {
3279 throw new SecurityException("Requires permission "
3280 + android.Manifest.permission.DEVICE_POWER);
3281 }
3282
3283 synchronized (mGlobalLock) {
3284 long ident = Binder.clearCallingIdentity();
3285 if (mKeyguardShown != keyguardShowing) {
3286 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003287 final Message msg = PooledLambda.obtainMessage(
3288 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3289 keyguardShowing);
3290 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003291 }
3292 try {
wilsonshih177261f2019-02-22 12:02:18 +08003293 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003294 } finally {
3295 Binder.restoreCallingIdentity(ident);
3296 }
3297 }
3298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003299 mH.post(() -> {
3300 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3301 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3302 }
3303 });
3304 }
3305
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003306 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003307 mH.post(() -> {
3308 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3309 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3310 }
3311 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003312 }
3313
3314 @Override
3315 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003316 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3317 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318
3319 final File passedIconFile = new File(filePath);
3320 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3321 passedIconFile.getName());
3322 if (!legitIconFile.getPath().equals(filePath)
3323 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3324 throw new IllegalArgumentException("Bad file path: " + filePath
3325 + " passed for userId " + userId);
3326 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003327 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003328 }
3329
3330 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003331 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3333 final ActivityOptions activityOptions = safeOptions != null
3334 ? safeOptions.getOptions(mStackSupervisor)
3335 : null;
3336 if (activityOptions == null
3337 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3338 || activityOptions.getCustomInPlaceResId() == 0) {
3339 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3340 "with valid animation");
3341 }
lumark588a3e82018-07-20 18:53:54 +08003342 // Get top display of front most application.
3343 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3344 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003345 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3346 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3347 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003348 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003349 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003350 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 }
3352
3353 @Override
3354 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003355 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 synchronized (mGlobalLock) {
3357 final long ident = Binder.clearCallingIdentity();
3358 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003359 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003360 if (stack == null) {
3361 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3362 return;
3363 }
3364 if (!stack.isActivityTypeStandardOrUndefined()) {
3365 throw new IllegalArgumentException(
3366 "Removing non-standard stack is not allowed.");
3367 }
3368 mStackSupervisor.removeStack(stack);
3369 } finally {
3370 Binder.restoreCallingIdentity(ident);
3371 }
3372 }
3373 }
3374
3375 @Override
3376 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003377 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378
3379 synchronized (mGlobalLock) {
3380 final long ident = Binder.clearCallingIdentity();
3381 try {
3382 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3383 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003384 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003385 } finally {
3386 Binder.restoreCallingIdentity(ident);
3387 }
3388 }
3389 }
3390
3391 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003392 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 synchronized (mGlobalLock) {
3394 long ident = Binder.clearCallingIdentity();
3395 try {
3396 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3397 if (r == null) {
3398 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003399 "toggleFreeformWindowingMode: No activity record matching token="
3400 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 }
3402
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003403 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003404 if (stack == null) {
3405 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3406 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003407 }
3408
Yunfan Chend967af82019-01-17 18:30:18 +09003409 if (!stack.inFreeformWindowingMode()
3410 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3411 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3412 + "toggle between fullscreen and freeform.");
3413 }
3414
3415 if (stack.inFreeformWindowingMode()) {
3416 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003417 } else if (stack.getParent().inFreeformWindowingMode()) {
3418 // If the window is on a freeform display, set it to undefined. It will be
3419 // resolved to freeform and it can adjust windowing mode when the display mode
3420 // changes in runtime.
3421 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003422 } else {
3423 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3424 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 } finally {
3426 Binder.restoreCallingIdentity(ident);
3427 }
3428 }
3429 }
3430
3431 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3432 @Override
3433 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003435 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003436 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003437 }
3438
3439 /** Unregister a task stack listener so that it stops receiving callbacks. */
3440 @Override
3441 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003442 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003443 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003444 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003445 }
3446
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 @Override
3448 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3449 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3450 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3451 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3452 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3453 }
3454
3455 @Override
3456 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3457 IBinder activityToken, int flags) {
3458 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3459 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3460 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3461 }
3462
3463 @Override
3464 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3465 Bundle args) {
3466 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3467 true /* focused */, true /* newSessionId */, userHandle, args,
3468 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3469 }
3470
3471 @Override
3472 public Bundle getAssistContextExtras(int requestType) {
3473 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3474 null, null, true /* focused */, true /* newSessionId */,
3475 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3476 if (pae == null) {
3477 return null;
3478 }
3479 synchronized (pae) {
3480 while (!pae.haveResult) {
3481 try {
3482 pae.wait();
3483 } catch (InterruptedException e) {
3484 }
3485 }
3486 }
3487 synchronized (mGlobalLock) {
3488 buildAssistBundleLocked(pae, pae.result);
3489 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003490 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003491 }
3492 return pae.extras;
3493 }
3494
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003495 /**
3496 * Binder IPC calls go through the public entry point.
3497 * This can be called with or without the global lock held.
3498 */
3499 private static int checkCallingPermission(String permission) {
3500 return checkPermission(
3501 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3502 }
3503
3504 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003505 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3507 mAmInternal.enforceCallingPermission(permission, func);
3508 }
3509 }
3510
3511 @VisibleForTesting
3512 int checkGetTasksPermission(String permission, int pid, int uid) {
3513 return checkPermission(permission, pid, uid);
3514 }
3515
3516 static int checkPermission(String permission, int pid, int uid) {
3517 if (permission == null) {
3518 return PackageManager.PERMISSION_DENIED;
3519 }
3520 return checkComponentPermission(permission, pid, uid, -1, true);
3521 }
3522
Wale Ogunwale214f3482018-10-04 11:00:47 -07003523 public static int checkComponentPermission(String permission, int pid, int uid,
3524 int owningUid, boolean exported) {
3525 return ActivityManagerService.checkComponentPermission(
3526 permission, pid, uid, owningUid, exported);
3527 }
3528
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003529 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3530 if (getRecentTasks().isCallerRecents(callingUid)) {
3531 // Always allow the recents component to get tasks
3532 return true;
3533 }
3534
3535 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3536 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3537 if (!allowed) {
3538 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3539 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3540 // Temporary compatibility: some existing apps on the system image may
3541 // still be requesting the old permission and not switched to the new
3542 // one; if so, we'll still allow them full access. This means we need
3543 // to see if they are holding the old permission and are a system app.
3544 try {
3545 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3546 allowed = true;
3547 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3548 + " is using old GET_TASKS but privileged; allowing");
3549 }
3550 } catch (RemoteException e) {
3551 }
3552 }
3553 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3554 + " does not hold REAL_GET_TASKS; limiting output");
3555 }
3556 return allowed;
3557 }
3558
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3560 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3561 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3562 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003563 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003564 "enqueueAssistContext()");
3565
3566 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003567 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003568 if (activity == null) {
3569 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3570 return null;
3571 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003572 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003573 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3574 return null;
3575 }
3576 if (focused) {
3577 if (activityToken != null) {
3578 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3579 if (activity != caller) {
3580 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3581 + " is not current top " + activity);
3582 return null;
3583 }
3584 }
3585 } else {
3586 activity = ActivityRecord.forTokenLocked(activityToken);
3587 if (activity == null) {
3588 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3589 + " couldn't be found");
3590 return null;
3591 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003592 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003593 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3594 return null;
3595 }
3596 }
3597
3598 PendingAssistExtras pae;
3599 Bundle extras = new Bundle();
3600 if (args != null) {
3601 extras.putAll(args);
3602 }
3603 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003604 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605
3606 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3607 userHandle);
3608 pae.isHome = activity.isActivityTypeHome();
3609
3610 // Increment the sessionId if necessary
3611 if (newSessionId) {
3612 mViSessionId++;
3613 }
3614 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003615 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3616 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003617 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003618 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003619 } catch (RemoteException e) {
3620 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3621 return null;
3622 }
3623 return pae;
3624 }
3625 }
3626
3627 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3628 if (result != null) {
3629 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3630 }
3631 if (pae.hint != null) {
3632 pae.extras.putBoolean(pae.hint, true);
3633 }
3634 }
3635
3636 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3637 IAssistDataReceiver receiver;
3638 synchronized (mGlobalLock) {
3639 mPendingAssistExtras.remove(pae);
3640 receiver = pae.receiver;
3641 }
3642 if (receiver != null) {
3643 // Caller wants result sent back to them.
3644 Bundle sendBundle = new Bundle();
3645 // At least return the receiver extras
3646 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3647 try {
3648 pae.receiver.onHandleAssistData(sendBundle);
3649 } catch (RemoteException e) {
3650 }
3651 }
3652 }
3653
3654 public class PendingAssistExtras extends Binder implements Runnable {
3655 public final ActivityRecord activity;
3656 public boolean isHome;
3657 public final Bundle extras;
3658 public final Intent intent;
3659 public final String hint;
3660 public final IAssistDataReceiver receiver;
3661 public final int userHandle;
3662 public boolean haveResult = false;
3663 public Bundle result = null;
3664 public AssistStructure structure = null;
3665 public AssistContent content = null;
3666 public Bundle receiverExtras;
3667
3668 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3669 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3670 int _userHandle) {
3671 activity = _activity;
3672 extras = _extras;
3673 intent = _intent;
3674 hint = _hint;
3675 receiver = _receiver;
3676 receiverExtras = _receiverExtras;
3677 userHandle = _userHandle;
3678 }
3679
3680 @Override
3681 public void run() {
3682 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3683 synchronized (this) {
3684 haveResult = true;
3685 notifyAll();
3686 }
3687 pendingAssistExtrasTimedOut(this);
3688 }
3689 }
3690
3691 @Override
3692 public boolean isAssistDataAllowedOnCurrentActivity() {
3693 int userId;
3694 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003695 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3697 return false;
3698 }
3699
3700 final ActivityRecord activity = focusedStack.getTopActivity();
3701 if (activity == null) {
3702 return false;
3703 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003704 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003705 }
3706 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3707 }
3708
3709 @Override
3710 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3711 long ident = Binder.clearCallingIdentity();
3712 try {
3713 synchronized (mGlobalLock) {
3714 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003715 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 if (top != caller) {
3717 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3718 + " is not current top " + top);
3719 return false;
3720 }
3721 if (!top.nowVisible) {
3722 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3723 + " is not visible");
3724 return false;
3725 }
3726 }
3727 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3728 token);
3729 } finally {
3730 Binder.restoreCallingIdentity(ident);
3731 }
3732 }
3733
3734 @Override
3735 public boolean isRootVoiceInteraction(IBinder token) {
3736 synchronized (mGlobalLock) {
3737 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3738 if (r == null) {
3739 return false;
3740 }
3741 return r.rootVoiceInteraction;
3742 }
3743 }
3744
Wale Ogunwalef6733932018-06-27 05:14:34 -07003745 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3746 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3747 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3748 if (activityToCallback == null) return;
3749 activityToCallback.setVoiceSessionLocked(voiceSession);
3750
3751 // Inform the activity
3752 try {
3753 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3754 voiceInteractor);
3755 long token = Binder.clearCallingIdentity();
3756 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003757 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003758 } finally {
3759 Binder.restoreCallingIdentity(token);
3760 }
3761 // TODO: VI Should we cache the activity so that it's easier to find later
3762 // rather than scan through all the stacks and activities?
3763 } catch (RemoteException re) {
3764 activityToCallback.clearVoiceSessionLocked();
3765 // TODO: VI Should this terminate the voice session?
3766 }
3767 }
3768
3769 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3770 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3771 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3772 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3773 boolean wasRunningVoice = mRunningVoice != null;
3774 mRunningVoice = session;
3775 if (!wasRunningVoice) {
3776 mVoiceWakeLock.acquire();
3777 updateSleepIfNeededLocked();
3778 }
3779 }
3780 }
3781
3782 void finishRunningVoiceLocked() {
3783 if (mRunningVoice != null) {
3784 mRunningVoice = null;
3785 mVoiceWakeLock.release();
3786 updateSleepIfNeededLocked();
3787 }
3788 }
3789
3790 @Override
3791 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3792 synchronized (mGlobalLock) {
3793 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3794 if (keepAwake) {
3795 mVoiceWakeLock.acquire();
3796 } else {
3797 mVoiceWakeLock.release();
3798 }
3799 }
3800 }
3801 }
3802
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003803 @Override
3804 public ComponentName getActivityClassForToken(IBinder token) {
3805 synchronized (mGlobalLock) {
3806 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3807 if (r == null) {
3808 return null;
3809 }
3810 return r.intent.getComponent();
3811 }
3812 }
3813
3814 @Override
3815 public String getPackageForToken(IBinder token) {
3816 synchronized (mGlobalLock) {
3817 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3818 if (r == null) {
3819 return null;
3820 }
3821 return r.packageName;
3822 }
3823 }
3824
3825 @Override
3826 public void showLockTaskEscapeMessage(IBinder token) {
3827 synchronized (mGlobalLock) {
3828 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3829 if (r == null) {
3830 return;
3831 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003832 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 }
3834 }
3835
3836 @Override
3837 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003838 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 final long token = Binder.clearCallingIdentity();
3840 try {
3841 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003842 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 }
3844 } finally {
3845 Binder.restoreCallingIdentity(token);
3846 }
3847 }
3848
3849 /**
3850 * Try to place task to provided position. The final position might be different depending on
3851 * current user and stacks state. The task will be moved to target stack if it's currently in
3852 * different stack.
3853 */
3854 @Override
3855 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003856 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003857 synchronized (mGlobalLock) {
3858 long ident = Binder.clearCallingIdentity();
3859 try {
3860 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3861 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003862 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003863 if (task == null) {
3864 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3865 + taskId);
3866 }
3867
Wale Ogunwaled32da472018-11-16 07:19:28 -08003868 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003869
3870 if (stack == null) {
3871 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3872 + stackId);
3873 }
3874 if (!stack.isActivityTypeStandardOrUndefined()) {
3875 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3876 + " the position of task " + taskId + " in/to non-standard stack");
3877 }
3878
3879 // TODO: Have the callers of this API call a separate reparent method if that is
3880 // what they intended to do vs. having this method also do reparenting.
3881 if (task.getStack() == stack) {
3882 // Change position in current stack.
3883 stack.positionChildAt(task, position);
3884 } else {
3885 // Reparent to new stack.
3886 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3887 !DEFER_RESUME, "positionTaskInStack");
3888 }
3889 } finally {
3890 Binder.restoreCallingIdentity(ident);
3891 }
3892 }
3893 }
3894
3895 @Override
3896 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3897 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3898 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003899 + Arrays.toString(horizontalSizeConfiguration) + " "
3900 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003901 synchronized (mGlobalLock) {
3902 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3903 if (record == null) {
3904 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3905 + "found for: " + token);
3906 }
3907 record.setSizeConfigurations(horizontalSizeConfiguration,
3908 verticalSizeConfigurations, smallestSizeConfigurations);
3909 }
3910 }
3911
3912 /**
3913 * Dismisses split-screen multi-window mode.
3914 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3915 */
3916 @Override
3917 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003918 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003919 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3920 final long ident = Binder.clearCallingIdentity();
3921 try {
3922 synchronized (mGlobalLock) {
3923 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003924 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003925 if (stack == null) {
3926 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3927 return;
3928 }
3929
3930 if (toTop) {
3931 // Caller wants the current split-screen primary stack to be the top stack after
3932 // it goes fullscreen, so move it to the front.
3933 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003934 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003936 // stack after it goes fullscreen, so we move the focus to the top-most
3937 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3939 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3940 if (otherStack != null) {
3941 otherStack.moveToFront("dismissSplitScreenMode_other");
3942 }
3943 }
3944
Evan Rosky10475742018-09-05 19:02:48 -07003945 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 }
3947 } finally {
3948 Binder.restoreCallingIdentity(ident);
3949 }
3950 }
3951
3952 /**
3953 * Dismisses Pip
3954 * @param animate True if the dismissal should be animated.
3955 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3956 * default animation duration should be used.
3957 */
3958 @Override
3959 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003960 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 final long ident = Binder.clearCallingIdentity();
3962 try {
3963 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003964 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003965 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 if (stack == null) {
3967 Slog.w(TAG, "dismissPip: pinned stack not found.");
3968 return;
3969 }
3970 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3971 throw new IllegalArgumentException("Stack: " + stack
3972 + " doesn't support animated resize.");
3973 }
3974 if (animate) {
3975 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3976 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3977 } else {
3978 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3979 }
3980 }
3981 } finally {
3982 Binder.restoreCallingIdentity(ident);
3983 }
3984 }
3985
3986 @Override
3987 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 synchronized (mGlobalLock) {
3990 mSuppressResizeConfigChanges = suppress;
3991 }
3992 }
3993
3994 /**
3995 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3996 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3997 * activity and clearing the task at the same time.
3998 */
3999 @Override
4000 // TODO: API should just be about changing windowing modes...
4001 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004002 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 "moveTasksToFullscreenStack()");
4004 synchronized (mGlobalLock) {
4005 final long origId = Binder.clearCallingIdentity();
4006 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004007 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 if (stack != null){
4009 if (!stack.isActivityTypeStandardOrUndefined()) {
4010 throw new IllegalArgumentException(
4011 "You can't move tasks from non-standard stacks.");
4012 }
4013 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4014 }
4015 } finally {
4016 Binder.restoreCallingIdentity(origId);
4017 }
4018 }
4019 }
4020
4021 /**
4022 * Moves the top activity in the input stackId to the pinned stack.
4023 *
4024 * @param stackId Id of stack to move the top activity to pinned stack.
4025 * @param bounds Bounds to use for pinned stack.
4026 *
4027 * @return True if the top activity of the input stack was successfully moved to the pinned
4028 * stack.
4029 */
4030 @Override
4031 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 "moveTopActivityToPinnedStack()");
4034 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004035 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4037 + "Device doesn't support picture-in-picture mode");
4038 }
4039
4040 long ident = Binder.clearCallingIdentity();
4041 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004042 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 } finally {
4044 Binder.restoreCallingIdentity(ident);
4045 }
4046 }
4047 }
4048
4049 @Override
4050 public boolean isInMultiWindowMode(IBinder token) {
4051 final long origId = Binder.clearCallingIdentity();
4052 try {
4053 synchronized (mGlobalLock) {
4054 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4055 if (r == null) {
4056 return false;
4057 }
4058 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4059 return r.inMultiWindowMode();
4060 }
4061 } finally {
4062 Binder.restoreCallingIdentity(origId);
4063 }
4064 }
4065
4066 @Override
4067 public boolean isInPictureInPictureMode(IBinder token) {
4068 final long origId = Binder.clearCallingIdentity();
4069 try {
4070 synchronized (mGlobalLock) {
4071 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4072 }
4073 } finally {
4074 Binder.restoreCallingIdentity(origId);
4075 }
4076 }
4077
4078 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004079 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4080 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 return false;
4082 }
4083
4084 // If we are animating to fullscreen then we have already dispatched the PIP mode
4085 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004086 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4087 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 }
4089
4090 @Override
4091 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4092 final long origId = Binder.clearCallingIdentity();
4093 try {
4094 synchronized (mGlobalLock) {
4095 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4096 "enterPictureInPictureMode", token, params);
4097
4098 // If the activity is already in picture in picture mode, then just return early
4099 if (isInPictureInPictureMode(r)) {
4100 return true;
4101 }
4102
4103 // Activity supports picture-in-picture, now check that we can enter PiP at this
4104 // point, if it is
4105 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4106 false /* beforeStopping */)) {
4107 return false;
4108 }
4109
4110 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004111 synchronized (mGlobalLock) {
4112 // Only update the saved args from the args that are set
4113 r.pictureInPictureArgs.copyOnlySet(params);
4114 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4115 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4116 // Adjust the source bounds by the insets for the transition down
4117 final Rect sourceBounds = new Rect(
4118 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004119 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004120 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004121 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004122 stack.setPictureInPictureAspectRatio(aspectRatio);
4123 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004124 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4125 r.info.applicationInfo.uid, r.shortComponentName,
4126 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004127 logPictureInPictureArgs(params);
4128 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 };
4130
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004131 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 // If the keyguard is showing or occluded, then try and dismiss it before
4133 // entering picture-in-picture (this will prompt the user to authenticate if the
4134 // device is currently locked).
4135 dismissKeyguard(token, new KeyguardDismissCallback() {
4136 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004137 public void onDismissSucceeded() {
4138 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139 }
4140 }, null /* message */);
4141 } else {
4142 // Enter picture in picture immediately otherwise
4143 enterPipRunnable.run();
4144 }
4145 return true;
4146 }
4147 } finally {
4148 Binder.restoreCallingIdentity(origId);
4149 }
4150 }
4151
4152 @Override
4153 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4154 final long origId = Binder.clearCallingIdentity();
4155 try {
4156 synchronized (mGlobalLock) {
4157 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4158 "setPictureInPictureParams", token, params);
4159
4160 // Only update the saved args from the args that are set
4161 r.pictureInPictureArgs.copyOnlySet(params);
4162 if (r.inPinnedWindowingMode()) {
4163 // If the activity is already in picture-in-picture, update the pinned stack now
4164 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4165 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004166 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004167 if (!stack.isAnimatingBoundsToFullscreen()) {
4168 stack.setPictureInPictureAspectRatio(
4169 r.pictureInPictureArgs.getAspectRatio());
4170 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4171 }
4172 }
4173 logPictureInPictureArgs(params);
4174 }
4175 } finally {
4176 Binder.restoreCallingIdentity(origId);
4177 }
4178 }
4179
4180 @Override
4181 public int getMaxNumPictureInPictureActions(IBinder token) {
4182 // Currently, this is a static constant, but later, we may change this to be dependent on
4183 // the context of the activity
4184 return 3;
4185 }
4186
4187 private void logPictureInPictureArgs(PictureInPictureParams params) {
4188 if (params.hasSetActions()) {
4189 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4190 params.getActions().size());
4191 }
4192 if (params.hasSetAspectRatio()) {
4193 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4194 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4195 MetricsLogger.action(lm);
4196 }
4197 }
4198
4199 /**
4200 * Checks the state of the system and the activity associated with the given {@param token} to
4201 * verify that picture-in-picture is supported for that activity.
4202 *
4203 * @return the activity record for the given {@param token} if all the checks pass.
4204 */
4205 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4206 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004207 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004208 throw new IllegalStateException(caller
4209 + ": Device doesn't support picture-in-picture mode.");
4210 }
4211
4212 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4213 if (r == null) {
4214 throw new IllegalStateException(caller
4215 + ": Can't find activity for token=" + token);
4216 }
4217
4218 if (!r.supportsPictureInPicture()) {
4219 throw new IllegalStateException(caller
4220 + ": Current activity does not support picture-in-picture.");
4221 }
4222
4223 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004224 && !mWindowManager.isValidPictureInPictureAspectRatio(
4225 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004226 final float minAspectRatio = mContext.getResources().getFloat(
4227 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4228 final float maxAspectRatio = mContext.getResources().getFloat(
4229 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4230 throw new IllegalArgumentException(String.format(caller
4231 + ": Aspect ratio is too extreme (must be between %f and %f).",
4232 minAspectRatio, maxAspectRatio));
4233 }
4234
4235 // Truncate the number of actions if necessary
4236 params.truncateActions(getMaxNumPictureInPictureActions(token));
4237
4238 return r;
4239 }
4240
4241 @Override
4242 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004243 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 synchronized (mGlobalLock) {
4245 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4246 if (r == null) {
4247 throw new IllegalArgumentException("Activity does not exist; token="
4248 + activityToken);
4249 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004250 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 }
4252 }
4253
4254 @Override
4255 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4256 Rect tempDockedTaskInsetBounds,
4257 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004258 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 long ident = Binder.clearCallingIdentity();
4260 try {
4261 synchronized (mGlobalLock) {
4262 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4263 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4264 PRESERVE_WINDOWS);
4265 }
4266 } finally {
4267 Binder.restoreCallingIdentity(ident);
4268 }
4269 }
4270
4271 @Override
4272 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 final long ident = Binder.clearCallingIdentity();
4275 try {
4276 synchronized (mGlobalLock) {
4277 mStackSupervisor.setSplitScreenResizing(resizing);
4278 }
4279 } finally {
4280 Binder.restoreCallingIdentity(ident);
4281 }
4282 }
4283
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004284 /**
4285 * Check that we have the features required for VR-related API calls, and throw an exception if
4286 * not.
4287 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004288 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004289 if (!mContext.getPackageManager().hasSystemFeature(
4290 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4291 throw new UnsupportedOperationException("VR mode not supported on this device!");
4292 }
4293 }
4294
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004295 @Override
4296 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298
4299 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4300
4301 ActivityRecord r;
4302 synchronized (mGlobalLock) {
4303 r = ActivityRecord.isInStackLocked(token);
4304 }
4305
4306 if (r == null) {
4307 throw new IllegalArgumentException();
4308 }
4309
4310 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004311 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 VrManagerInternal.NO_ERROR) {
4313 return err;
4314 }
4315
4316 // Clear the binder calling uid since this path may call moveToTask().
4317 final long callingId = Binder.clearCallingIdentity();
4318 try {
4319 synchronized (mGlobalLock) {
4320 r.requestedVrComponent = (enabled) ? packageName : null;
4321
4322 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004323 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004324 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 }
4326 return 0;
4327 }
4328 } finally {
4329 Binder.restoreCallingIdentity(callingId);
4330 }
4331 }
4332
4333 @Override
4334 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4335 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4336 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004337 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004338 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4339 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4340 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004341 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 || activity.voiceSession != null) {
4343 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4344 return;
4345 }
4346 if (activity.pendingVoiceInteractionStart) {
4347 Slog.w(TAG, "Pending start of voice interaction already.");
4348 return;
4349 }
4350 activity.pendingVoiceInteractionStart = true;
4351 }
4352 LocalServices.getService(VoiceInteractionManagerInternal.class)
4353 .startLocalVoiceInteraction(callingActivity, options);
4354 }
4355
4356 @Override
4357 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4358 LocalServices.getService(VoiceInteractionManagerInternal.class)
4359 .stopLocalVoiceInteraction(callingActivity);
4360 }
4361
4362 @Override
4363 public boolean supportsLocalVoiceInteraction() {
4364 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4365 .supportsLocalVoiceInteraction();
4366 }
4367
4368 /** Notifies all listeners when the pinned stack animation starts. */
4369 @Override
4370 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004371 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004372 }
4373
4374 /** Notifies all listeners when the pinned stack animation ends. */
4375 @Override
4376 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004377 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004378 }
4379
4380 @Override
4381 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004382 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383 final long ident = Binder.clearCallingIdentity();
4384 try {
4385 synchronized (mGlobalLock) {
4386 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4387 }
4388 } finally {
4389 Binder.restoreCallingIdentity(ident);
4390 }
4391 }
4392
4393 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004395 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396
4397 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004398 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 }
4402
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004403 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004404 final Message msg = PooledLambda.obtainMessage(
4405 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4406 DEFAULT_DISPLAY);
4407 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 }
4409
4410 final long origId = Binder.clearCallingIdentity();
4411 try {
4412 if (values != null) {
4413 Settings.System.clearConfiguration(values);
4414 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004415 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 UserHandle.USER_NULL, false /* deferResume */,
4417 mTmpUpdateConfigurationResult);
4418 return mTmpUpdateConfigurationResult.changes != 0;
4419 } finally {
4420 Binder.restoreCallingIdentity(origId);
4421 }
4422 }
4423 }
4424
4425 @Override
4426 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4427 CharSequence message) {
4428 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004429 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4431 }
4432 final long callingId = Binder.clearCallingIdentity();
4433 try {
4434 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004435 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 }
4437 } finally {
4438 Binder.restoreCallingIdentity(callingId);
4439 }
4440 }
4441
4442 @Override
4443 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004444 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004445 "cancelTaskWindowTransition()");
4446 final long ident = Binder.clearCallingIdentity();
4447 try {
4448 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004449 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004450 MATCH_TASK_IN_STACKS_ONLY);
4451 if (task == null) {
4452 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4453 return;
4454 }
4455 task.cancelWindowTransition();
4456 }
4457 } finally {
4458 Binder.restoreCallingIdentity(ident);
4459 }
4460 }
4461
4462 @Override
4463 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004464 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004465 final long ident = Binder.clearCallingIdentity();
4466 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004467 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004468 } finally {
4469 Binder.restoreCallingIdentity(ident);
4470 }
4471 }
4472
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004473 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4474 boolean restoreFromDisk) {
4475 final TaskRecord task;
4476 synchronized (mGlobalLock) {
4477 task = mRootActivityContainer.anyTaskForId(taskId,
4478 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4479 if (task == null) {
4480 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4481 return null;
4482 }
4483 }
4484 // Don't call this while holding the lock as this operation might hit the disk.
4485 return task.getSnapshot(reducedResolution, restoreFromDisk);
4486 }
4487
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004488 @Override
4489 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4490 synchronized (mGlobalLock) {
4491 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4492 if (r == null) {
4493 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4494 + token);
4495 return;
4496 }
4497 final long origId = Binder.clearCallingIdentity();
4498 try {
4499 r.setDisablePreviewScreenshots(disable);
4500 } finally {
4501 Binder.restoreCallingIdentity(origId);
4502 }
4503 }
4504 }
4505
4506 /** Return the user id of the last resumed activity. */
4507 @Override
4508 public @UserIdInt
4509 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4512 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004513 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004516 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void updateLockTaskFeatures(int userId, int flags) {
4522 final int callingUid = Binder.getCallingUid();
4523 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004524 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004525 "updateLockTaskFeatures()");
4526 }
4527 synchronized (mGlobalLock) {
4528 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4529 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004530 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004531 }
4532 }
4533
4534 @Override
4535 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4536 synchronized (mGlobalLock) {
4537 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4538 if (r == null) {
4539 return;
4540 }
4541 final long origId = Binder.clearCallingIdentity();
4542 try {
4543 r.setShowWhenLocked(showWhenLocked);
4544 } finally {
4545 Binder.restoreCallingIdentity(origId);
4546 }
4547 }
4548 }
4549
4550 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004551 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4552 synchronized (mGlobalLock) {
4553 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4554 if (r == null) {
4555 return;
4556 }
4557 final long origId = Binder.clearCallingIdentity();
4558 try {
4559 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4560 } finally {
4561 Binder.restoreCallingIdentity(origId);
4562 }
4563 }
4564 }
4565
4566 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004567 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4568 synchronized (mGlobalLock) {
4569 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4570 if (r == null) {
4571 return;
4572 }
4573 final long origId = Binder.clearCallingIdentity();
4574 try {
4575 r.setTurnScreenOn(turnScreenOn);
4576 } finally {
4577 Binder.restoreCallingIdentity(origId);
4578 }
4579 }
4580 }
4581
4582 @Override
4583 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004584 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004585 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004586 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 synchronized (mGlobalLock) {
4588 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4589 if (r == null) {
4590 return;
4591 }
4592 final long origId = Binder.clearCallingIdentity();
4593 try {
4594 r.registerRemoteAnimations(definition);
4595 } finally {
4596 Binder.restoreCallingIdentity(origId);
4597 }
4598 }
4599 }
4600
4601 @Override
4602 public void registerRemoteAnimationForNextActivityStart(String packageName,
4603 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004604 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004605 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004606 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004607 synchronized (mGlobalLock) {
4608 final long origId = Binder.clearCallingIdentity();
4609 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004610 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004611 packageName, adapter);
4612 } finally {
4613 Binder.restoreCallingIdentity(origId);
4614 }
4615 }
4616 }
4617
Evan Rosky966759f2019-01-15 10:33:58 -08004618 @Override
4619 public void registerRemoteAnimationsForDisplay(int displayId,
4620 RemoteAnimationDefinition definition) {
4621 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4622 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004623 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004624 synchronized (mGlobalLock) {
4625 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4626 if (display == null) {
4627 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4628 return;
4629 }
4630 final long origId = Binder.clearCallingIdentity();
4631 try {
4632 display.mDisplayContent.registerRemoteAnimations(definition);
4633 } finally {
4634 Binder.restoreCallingIdentity(origId);
4635 }
4636 }
4637 }
4638
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4640 @Override
4641 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4642 synchronized (mGlobalLock) {
4643 final long origId = Binder.clearCallingIdentity();
4644 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004645 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004646 } finally {
4647 Binder.restoreCallingIdentity(origId);
4648 }
4649 }
4650 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004651
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004652 @Override
4653 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004654 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004655 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004656 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004657 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004658 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 }
4660 }
4661
4662 @Override
4663 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004664 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004665 != PERMISSION_GRANTED) {
4666 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4667 + Binder.getCallingPid()
4668 + ", uid=" + Binder.getCallingUid()
4669 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4670 Slog.w(TAG, msg);
4671 throw new SecurityException(msg);
4672 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004674 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004675 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004676 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004677 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004678 }
4679 }
4680
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004681 @Override
4682 public void stopAppSwitches() {
4683 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4684 synchronized (mGlobalLock) {
4685 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004686 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 mDidAppSwitch = false;
4688 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4689 }
4690 }
4691
4692 @Override
4693 public void resumeAppSwitches() {
4694 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4695 synchronized (mGlobalLock) {
4696 // Note that we don't execute any pending app switches... we will
4697 // let those wait until either the timeout, or the next start
4698 // activity request.
4699 mAppSwitchesAllowedTime = 0;
4700 }
4701 }
4702
Ricky Wai906af482019-06-03 17:25:28 +01004703 long getLastStopAppSwitchesTime() {
4704 return mLastStopAppSwitchesTime;
4705 }
4706
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004707 void onStartActivitySetDidAppSwitch() {
4708 if (mDidAppSwitch) {
4709 // This is the second allowed switch since we stopped switches, so now just generally
4710 // allow switches. Use case:
4711 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4712 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4713 // anyone to switch again).
4714 mAppSwitchesAllowedTime = 0;
4715 } else {
4716 mDidAppSwitch = true;
4717 }
4718 }
4719
4720 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004721 boolean shouldDisableNonVrUiLocked() {
4722 return mVrController.shouldDisableNonVrUiLocked();
4723 }
4724
Wale Ogunwale53783742018-09-16 10:21:51 -07004725 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004726 // 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 +00004727 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004728 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004729 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4730 + " to main display for VR");
4731 mRootActivityContainer.moveStackToDisplay(
4732 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004733 }
4734 mH.post(() -> {
4735 if (!mVrController.onVrModeChanged(r)) {
4736 return;
4737 }
4738 synchronized (mGlobalLock) {
4739 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4740 mWindowManager.disableNonVrUi(disableNonVrUi);
4741 if (disableNonVrUi) {
4742 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4743 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004744 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004745 }
4746 }
4747 });
4748 }
4749
Wale Ogunwale53783742018-09-16 10:21:51 -07004750 @Override
4751 public int getPackageScreenCompatMode(String packageName) {
4752 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4753 synchronized (mGlobalLock) {
4754 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4755 }
4756 }
4757
4758 @Override
4759 public void setPackageScreenCompatMode(String packageName, int mode) {
4760 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4761 "setPackageScreenCompatMode");
4762 synchronized (mGlobalLock) {
4763 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4764 }
4765 }
4766
4767 @Override
4768 public boolean getPackageAskScreenCompat(String packageName) {
4769 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4770 synchronized (mGlobalLock) {
4771 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4772 }
4773 }
4774
4775 @Override
4776 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4777 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4778 "setPackageAskScreenCompat");
4779 synchronized (mGlobalLock) {
4780 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4781 }
4782 }
4783
Wale Ogunwale64258362018-10-16 15:13:37 -07004784 public static String relaunchReasonToString(int relaunchReason) {
4785 switch (relaunchReason) {
4786 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4787 return "window_resize";
4788 case RELAUNCH_REASON_FREE_RESIZE:
4789 return "free_resize";
4790 default:
4791 return null;
4792 }
4793 }
4794
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004795 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004796 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004797 }
4798
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004799 /** Pokes the task persister. */
4800 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4801 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4802 }
4803
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004804 boolean isKeyguardLocked() {
4805 return mKeyguardController.isKeyguardLocked();
4806 }
4807
Garfield Tan01548632018-11-27 10:15:48 -08004808 /**
4809 * Clears launch params for the given package.
4810 * @param packageNames the names of the packages of which the launch params are to be cleared
4811 */
4812 @Override
4813 public void clearLaunchParamsForPackages(List<String> packageNames) {
4814 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4815 "clearLaunchParamsForPackages");
4816 synchronized (mGlobalLock) {
4817 for (int i = 0; i < packageNames.size(); ++i) {
4818 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4819 }
4820 }
4821 }
4822
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004823 /**
4824 * Makes the display with the given id a single task instance display. I.e the display can only
4825 * contain one task.
4826 */
4827 @Override
4828 public void setDisplayToSingleTaskInstance(int displayId) {
4829 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4830 "setDisplayToSingleTaskInstance");
4831 final long origId = Binder.clearCallingIdentity();
4832 try {
4833 final ActivityDisplay display =
4834 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4835 if (display != null) {
4836 display.setDisplayToSingleTaskInstance();
4837 }
4838 } finally {
4839 Binder.restoreCallingIdentity(origId);
4840 }
4841 }
4842
Wale Ogunwale31913b52018-10-13 08:29:31 -07004843 void dumpLastANRLocked(PrintWriter pw) {
4844 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4845 if (mLastANRState == null) {
4846 pw.println(" <no ANR has occurred since boot>");
4847 } else {
4848 pw.println(mLastANRState);
4849 }
4850 }
4851
4852 void dumpLastANRTracesLocked(PrintWriter pw) {
4853 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4854
4855 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4856 if (ArrayUtils.isEmpty(files)) {
4857 pw.println(" <no ANR has occurred since boot>");
4858 return;
4859 }
4860 // Find the latest file.
4861 File latest = null;
4862 for (File f : files) {
4863 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4864 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004865 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004866 }
4867 pw.print("File: ");
4868 pw.print(latest.getName());
4869 pw.println();
4870 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4871 String line;
4872 while ((line = in.readLine()) != null) {
4873 pw.println(line);
4874 }
4875 } catch (IOException e) {
4876 pw.print("Unable to read: ");
4877 pw.print(e);
4878 pw.println();
4879 }
4880 }
4881
4882 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4883 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4884 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4885 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4886 }
4887
4888 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4889 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4890 pw.println(header);
4891
Wale Ogunwaled32da472018-11-16 07:19:28 -08004892 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004893 dumpPackage);
4894 boolean needSep = printedAnything;
4895
4896 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004897 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004898 " ResumedActivity: ");
4899 if (printed) {
4900 printedAnything = true;
4901 needSep = false;
4902 }
4903
4904 if (dumpPackage == null) {
4905 if (needSep) {
4906 pw.println();
4907 }
4908 printedAnything = true;
4909 mStackSupervisor.dump(pw, " ");
4910 }
4911
4912 if (!printedAnything) {
4913 pw.println(" (nothing)");
4914 }
4915 }
4916
4917 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004918 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004919 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004920 pw.println(" ");
4921 }
4922
4923 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4924 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4925 getActivityStartController().dump(pw, "", dumpPackage);
4926 }
4927
4928 /**
4929 * There are three things that cmd can be:
4930 * - a flattened component name that matches an existing activity
4931 * - the cmd arg isn't the flattened component name of an existing activity:
4932 * dump all activity whose component contains the cmd as a substring
4933 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004934 * <p>
4935 * The caller should not hold lock when calling this method because it will wait for the
4936 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004937 *
4938 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4939 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4940 */
4941 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4942 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4943 ArrayList<ActivityRecord> activities;
4944
4945 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004946 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004947 dumpFocusedStackOnly);
4948 }
4949
4950 if (activities.size() <= 0) {
4951 return false;
4952 }
4953
4954 String[] newArgs = new String[args.length - opti];
4955 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4956
4957 TaskRecord lastTask = null;
4958 boolean needSep = false;
4959 for (int i = activities.size() - 1; i >= 0; i--) {
4960 ActivityRecord r = activities.get(i);
4961 if (needSep) {
4962 pw.println();
4963 }
4964 needSep = true;
4965 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004966 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004967 if (lastTask != task) {
4968 lastTask = task;
4969 pw.print("TASK "); pw.print(lastTask.affinity);
4970 pw.print(" id="); pw.print(lastTask.taskId);
4971 pw.print(" userId="); pw.println(lastTask.userId);
4972 if (dumpAll) {
4973 lastTask.dump(pw, " ");
4974 }
4975 }
4976 }
4977 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4978 }
4979 return true;
4980 }
4981
4982 /**
4983 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4984 * there is a thread associated with the activity.
4985 */
4986 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4987 final ActivityRecord r, String[] args, boolean dumpAll) {
4988 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004989 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004990 synchronized (mGlobalLock) {
4991 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4992 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4993 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004994 if (r.hasProcess()) {
4995 pw.println(r.app.getPid());
4996 appThread = r.app.getThread();
4997 } else {
4998 pw.println("(not running)");
4999 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07005000 if (dumpAll) {
5001 r.dump(pw, innerPrefix);
5002 }
5003 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005004 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07005005 // flush anything that is already in the PrintWriter since the thread is going
5006 // to write to the file descriptor directly
5007 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08005008 try (TransferPipe tp = new TransferPipe()) {
5009 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
5010 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07005011 } catch (IOException e) {
5012 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5013 } catch (RemoteException e) {
5014 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5015 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005016 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005017 }
5018
sanryhuang498e77e2018-12-06 14:57:01 +08005019 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5020 boolean testPssMode) {
5021 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5022 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5023 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005024 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005025 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5026 st.toString());
5027 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005028 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5029 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5030 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005031 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5032 testPssMode);
5033 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005034 }
5035
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005036 int getCurrentUserId() {
5037 return mAmInternal.getCurrentUserId();
5038 }
5039
5040 private void enforceNotIsolatedCaller(String caller) {
5041 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5042 throw new SecurityException("Isolated process not allowed to call " + caller);
5043 }
5044 }
5045
Wale Ogunwalef6733932018-06-27 05:14:34 -07005046 public Configuration getConfiguration() {
5047 Configuration ci;
5048 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005049 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005050 ci.userSetLocale = false;
5051 }
5052 return ci;
5053 }
5054
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005055 /**
5056 * Current global configuration information. Contains general settings for the entire system,
5057 * also corresponds to the merged configuration of the default display.
5058 */
5059 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005060 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061 }
5062
5063 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5064 boolean initLocale) {
5065 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5066 }
5067
5068 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5069 boolean initLocale, boolean deferResume) {
5070 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5071 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5072 UserHandle.USER_NULL, deferResume);
5073 }
5074
Wale Ogunwale59507092018-10-29 09:00:30 -07005075 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076 final long origId = Binder.clearCallingIdentity();
5077 try {
5078 synchronized (mGlobalLock) {
5079 updateConfigurationLocked(values, null, false, true, userId,
5080 false /* deferResume */);
5081 }
5082 } finally {
5083 Binder.restoreCallingIdentity(origId);
5084 }
5085 }
5086
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005087 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5088 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5089 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5090 deferResume, null /* result */);
5091 }
5092
5093 /**
5094 * Do either or both things: (1) change the current configuration, and (2)
5095 * make sure the given activity is running with the (now) current
5096 * configuration. Returns true if the activity has been left running, or
5097 * false if <var>starting</var> is being destroyed to match the new
5098 * configuration.
5099 *
5100 * @param userId is only used when persistent parameter is set to true to persist configuration
5101 * for that particular user
5102 */
5103 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5104 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5105 ActivityTaskManagerService.UpdateConfigurationResult result) {
5106 int changes = 0;
5107 boolean kept = true;
5108
5109 if (mWindowManager != null) {
5110 mWindowManager.deferSurfaceLayout();
5111 }
5112 try {
5113 if (values != null) {
5114 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5115 deferResume);
5116 }
5117
5118 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5119 } finally {
5120 if (mWindowManager != null) {
5121 mWindowManager.continueSurfaceLayout();
5122 }
5123 }
5124
5125 if (result != null) {
5126 result.changes = changes;
5127 result.activityRelaunched = !kept;
5128 }
5129 return kept;
5130 }
5131
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005133 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005135
5136 final ActivityDisplay defaultDisplay =
5137 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5138
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139 mTempConfig.setTo(getGlobalConfiguration());
5140 final int changes = mTempConfig.updateFrom(values);
5141 if (changes == 0) {
5142 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5143 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5144 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5145 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005146 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005147 return 0;
5148 }
5149
5150 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5151 "Updating global configuration to: " + values);
5152
5153 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5154 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5155 values.colorMode,
5156 values.densityDpi,
5157 values.fontScale,
5158 values.hardKeyboardHidden,
5159 values.keyboard,
5160 values.keyboardHidden,
5161 values.mcc,
5162 values.mnc,
5163 values.navigation,
5164 values.navigationHidden,
5165 values.orientation,
5166 values.screenHeightDp,
5167 values.screenLayout,
5168 values.screenWidthDp,
5169 values.smallestScreenWidthDp,
5170 values.touchscreen,
5171 values.uiMode);
5172
5173
5174 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5175 final LocaleList locales = values.getLocales();
5176 int bestLocaleIndex = 0;
5177 if (locales.size() > 1) {
5178 if (mSupportedSystemLocales == null) {
5179 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5180 }
5181 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5182 }
5183 SystemProperties.set("persist.sys.locale",
5184 locales.get(bestLocaleIndex).toLanguageTag());
5185 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005186
5187 final Message m = PooledLambda.obtainMessage(
5188 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5189 locales.get(bestLocaleIndex));
5190 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005191 }
5192
Yunfan Chen75157d72018-07-27 14:47:21 +09005193 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005194
5195 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005196 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005197
5198 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5199 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005200 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005201
5202 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005203 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005204
5205 AttributeCache ac = AttributeCache.instance();
5206 if (ac != null) {
5207 ac.updateConfiguration(mTempConfig);
5208 }
5209
5210 // Make sure all resources in our process are updated right now, so that anyone who is going
5211 // to retrieve resource values after we return will be sure to get the new ones. This is
5212 // especially important during boot, where the first config change needs to guarantee all
5213 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005214 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005215
5216 // We need another copy of global config because we're scheduling some calls instead of
5217 // running them in place. We need to be sure that object we send will be handled unchanged.
5218 final Configuration configCopy = new Configuration(mTempConfig);
5219 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005220 final Message msg = PooledLambda.obtainMessage(
5221 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5222 this, userId, configCopy);
5223 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224 }
5225
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005226 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5227 for (int i = pidMap.size() - 1; i >= 0; i--) {
5228 final int pid = pidMap.keyAt(i);
5229 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005230 if (DEBUG_CONFIGURATION) {
5231 Slog.v(TAG_CONFIGURATION, "Update process config of "
5232 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005233 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005234 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005235 }
5236
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005237 final Message msg = PooledLambda.obtainMessage(
5238 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5239 mAmInternal, changes, initLocale);
5240 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005241
5242 // Override configuration of the default display duplicates global config, so we need to
5243 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005244 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5245 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246
5247 return changes;
5248 }
5249
Wale Ogunwalef6733932018-06-27 05:14:34 -07005250 private void updateEventDispatchingLocked(boolean booted) {
5251 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5252 }
5253
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005254 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5255 final ContentResolver resolver = mContext.getContentResolver();
5256 Settings.System.putConfigurationForUser(resolver, config, userId);
5257 }
5258
5259 private void sendLocaleToMountDaemonMsg(Locale l) {
5260 try {
5261 IBinder service = ServiceManager.getService("mount");
5262 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5263 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5264 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5265 } catch (RemoteException e) {
5266 Log.e(TAG, "Error storing locale for decryption UI", e);
5267 }
5268 }
5269
Alison Cichowlas3e340502018-08-07 17:15:01 -04005270 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5271 mStartActivitySources.remove(permissionToken);
5272 mExpiredStartAsCallerTokens.add(permissionToken);
5273 }
5274
5275 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5276 mExpiredStartAsCallerTokens.remove(permissionToken);
5277 }
5278
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005279 boolean isActivityStartsLoggingEnabled() {
5280 return mAmInternal.isActivityStartsLoggingEnabled();
5281 }
5282
Michal Karpinski8596ded2018-11-14 14:43:48 +00005283 boolean isBackgroundActivityStartsEnabled() {
5284 return mAmInternal.isBackgroundActivityStartsEnabled();
5285 }
5286
Wale Ogunwalef6733932018-06-27 05:14:34 -07005287 void enableScreenAfterBoot(boolean booted) {
5288 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5289 SystemClock.uptimeMillis());
5290 mWindowManager.enableScreenAfterBoot();
5291
5292 synchronized (mGlobalLock) {
5293 updateEventDispatchingLocked(booted);
5294 }
5295 }
5296
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005297 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5298 if (r == null || !r.hasProcess()) {
5299 return KEY_DISPATCHING_TIMEOUT_MS;
5300 }
5301 return getInputDispatchingTimeoutLocked(r.app);
5302 }
5303
5304 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005305 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005306 }
5307
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 /**
5309 * Decide based on the configuration whether we should show the ANR,
5310 * crash, etc dialogs. The idea is that if there is no affordance to
5311 * press the on-screen buttons, or the user experience would be more
5312 * greatly impacted than the crash itself, we shouldn't show the dialog.
5313 *
5314 * A thought: SystemUI might also want to get told about this, the Power
5315 * dialog / global actions also might want different behaviors.
5316 */
5317 private void updateShouldShowDialogsLocked(Configuration config) {
5318 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5319 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5320 && config.navigation == Configuration.NAVIGATION_NONAV);
5321 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5322 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5323 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5324 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5325 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5326 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5327 HIDE_ERROR_DIALOGS, 0) != 0;
5328 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5329 }
5330
5331 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5332 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5333 FONT_SCALE, 1.0f, userId);
5334
5335 synchronized (this) {
5336 if (getGlobalConfiguration().fontScale == scaleFactor) {
5337 return;
5338 }
5339
5340 final Configuration configuration
5341 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5342 configuration.fontScale = scaleFactor;
5343 updatePersistentConfiguration(configuration, userId);
5344 }
5345 }
5346
5347 // Actually is sleeping or shutting down or whatever else in the future
5348 // is an inactive state.
5349 boolean isSleepingOrShuttingDownLocked() {
5350 return isSleepingLocked() || mShuttingDown;
5351 }
5352
5353 boolean isSleepingLocked() {
5354 return mSleeping;
5355 }
5356
Riddle Hsu16567132018-08-16 21:37:47 +08005357 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005359 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005360 if (task.isActivityTypeStandard()) {
5361 if (mCurAppTimeTracker != r.appTimeTracker) {
5362 // We are switching app tracking. Complete the current one.
5363 if (mCurAppTimeTracker != null) {
5364 mCurAppTimeTracker.stop();
5365 mH.obtainMessage(
5366 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005367 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005368 mCurAppTimeTracker = null;
5369 }
5370 if (r.appTimeTracker != null) {
5371 mCurAppTimeTracker = r.appTimeTracker;
5372 startTimeTrackingFocusedActivityLocked();
5373 }
5374 } else {
5375 startTimeTrackingFocusedActivityLocked();
5376 }
5377 } else {
5378 r.appTimeTracker = null;
5379 }
5380 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5381 // TODO: Probably not, because we don't want to resume voice on switching
5382 // back to this activity
5383 if (task.voiceInteractor != null) {
5384 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5385 } else {
5386 finishRunningVoiceLocked();
5387
5388 if (mLastResumedActivity != null) {
5389 final IVoiceInteractionSession session;
5390
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005391 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 if (lastResumedActivityTask != null
5393 && lastResumedActivityTask.voiceSession != null) {
5394 session = lastResumedActivityTask.voiceSession;
5395 } else {
5396 session = mLastResumedActivity.voiceSession;
5397 }
5398
5399 if (session != null) {
5400 // We had been in a voice interaction session, but now focused has
5401 // move to something different. Just finish the session, we can't
5402 // return to it and retain the proper state and synchronization with
5403 // the voice interaction service.
5404 finishVoiceTask(session);
5405 }
5406 }
5407 }
5408
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005409 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5410 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005411 }
5412 updateResumedAppTrace(r);
5413 mLastResumedActivity = r;
5414
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005415 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416
5417 applyUpdateLockStateLocked(r);
5418 applyUpdateVrModeLocked(r);
5419
5420 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005421 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422 r == null ? "NULL" : r.shortComponentName,
5423 reason);
5424 }
5425
5426 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5427 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005428 final ActivityTaskManagerInternal.SleepToken token =
5429 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005430 updateSleepIfNeededLocked();
5431 return token;
5432 }
5433 }
5434
5435 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005436 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 final boolean wasSleeping = mSleeping;
5438 boolean updateOomAdj = false;
5439
5440 if (!shouldSleep) {
5441 // If wasSleeping is true, we need to wake up activity manager state from when
5442 // we started sleeping. In either case, we need to apply the sleep tokens, which
5443 // will wake up stacks or put them to sleep as appropriate.
5444 if (wasSleeping) {
5445 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005446 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5447 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005448 startTimeTrackingFocusedActivityLocked();
5449 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005450 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005451 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5452 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005453 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 if (wasSleeping) {
5455 updateOomAdj = true;
5456 }
5457 } else if (!mSleeping && shouldSleep) {
5458 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005459 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5460 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 if (mCurAppTimeTracker != null) {
5462 mCurAppTimeTracker.stop();
5463 }
5464 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005465 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 mStackSupervisor.goingToSleepLocked();
5467 updateResumedAppTrace(null /* resumed */);
5468 updateOomAdj = true;
5469 }
5470 if (updateOomAdj) {
5471 mH.post(mAmInternal::updateOomAdj);
5472 }
5473 }
5474
5475 void updateOomAdj() {
5476 mH.post(mAmInternal::updateOomAdj);
5477 }
5478
Wale Ogunwale53783742018-09-16 10:21:51 -07005479 void updateCpuStats() {
5480 mH.post(mAmInternal::updateCpuStats);
5481 }
5482
Hui Yu03d12402018-12-06 18:00:37 -08005483 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5484 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005485 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5486 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005487 mH.sendMessage(m);
5488 }
5489
Hui Yu03d12402018-12-06 18:00:37 -08005490 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005491 ComponentName taskRoot = null;
5492 final TaskRecord task = activity.getTaskRecord();
5493 if (task != null) {
5494 final ActivityRecord rootActivity = task.getRootActivity();
5495 if (rootActivity != null) {
5496 taskRoot = rootActivity.mActivityComponent;
5497 }
5498 }
5499
Hui Yu03d12402018-12-06 18:00:37 -08005500 final Message m = PooledLambda.obtainMessage(
5501 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005502 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005503 mH.sendMessage(m);
5504 }
5505
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005506 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5507 String hostingType) {
5508 try {
5509 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5510 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5511 + activity.processName);
5512 }
5513 // Post message to start process to avoid possible deadlock of calling into AMS with the
5514 // ATMS lock held.
5515 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5516 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5517 isTop, hostingType, activity.intent.getComponent());
5518 mH.sendMessage(m);
5519 } finally {
5520 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5521 }
5522 }
5523
Wale Ogunwale53783742018-09-16 10:21:51 -07005524 void setBooting(boolean booting) {
5525 mAmInternal.setBooting(booting);
5526 }
5527
5528 boolean isBooting() {
5529 return mAmInternal.isBooting();
5530 }
5531
5532 void setBooted(boolean booted) {
5533 mAmInternal.setBooted(booted);
5534 }
5535
5536 boolean isBooted() {
5537 return mAmInternal.isBooted();
5538 }
5539
5540 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5541 mH.post(() -> {
5542 if (finishBooting) {
5543 mAmInternal.finishBooting();
5544 }
5545 if (enableScreen) {
5546 mInternal.enableScreenAfterBoot(isBooted());
5547 }
5548 });
5549 }
5550
5551 void setHeavyWeightProcess(ActivityRecord root) {
5552 mHeavyWeightProcess = root.app;
5553 final Message m = PooledLambda.obtainMessage(
5554 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005555 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005556 mH.sendMessage(m);
5557 }
5558
5559 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5560 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5561 return;
5562 }
5563
5564 mHeavyWeightProcess = null;
5565 final Message m = PooledLambda.obtainMessage(
5566 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5567 proc.mUserId);
5568 mH.sendMessage(m);
5569 }
5570
5571 private void cancelHeavyWeightProcessNotification(int userId) {
5572 final INotificationManager inm = NotificationManager.getService();
5573 if (inm == null) {
5574 return;
5575 }
5576 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005577 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005578 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5579 } catch (RuntimeException e) {
5580 Slog.w(TAG, "Error canceling notification for service", e);
5581 } catch (RemoteException e) {
5582 }
5583
5584 }
5585
5586 private void postHeavyWeightProcessNotification(
5587 WindowProcessController proc, Intent intent, int userId) {
5588 if (proc == null) {
5589 return;
5590 }
5591
5592 final INotificationManager inm = NotificationManager.getService();
5593 if (inm == null) {
5594 return;
5595 }
5596
5597 try {
5598 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5599 String text = mContext.getString(R.string.heavy_weight_notification,
5600 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5601 Notification notification =
5602 new Notification.Builder(context,
5603 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5604 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5605 .setWhen(0)
5606 .setOngoing(true)
5607 .setTicker(text)
5608 .setColor(mContext.getColor(
5609 com.android.internal.R.color.system_notification_accent_color))
5610 .setContentTitle(text)
5611 .setContentText(
5612 mContext.getText(R.string.heavy_weight_notification_detail))
5613 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5614 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5615 new UserHandle(userId)))
5616 .build();
5617 try {
5618 inm.enqueueNotificationWithTag("android", "android", null,
5619 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5620 } catch (RuntimeException e) {
5621 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5622 } catch (RemoteException e) {
5623 }
5624 } catch (PackageManager.NameNotFoundException e) {
5625 Slog.w(TAG, "Unable to create context for heavy notification", e);
5626 }
5627
5628 }
5629
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005630 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5631 IBinder token, String resultWho, int requestCode, Intent[] intents,
5632 String[] resolvedTypes, int flags, Bundle bOptions) {
5633
5634 ActivityRecord activity = null;
5635 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5636 activity = ActivityRecord.isInStackLocked(token);
5637 if (activity == null) {
5638 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5639 return null;
5640 }
5641 if (activity.finishing) {
5642 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5643 return null;
5644 }
5645 }
5646
5647 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5648 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5649 bOptions);
5650 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5651 if (noCreate) {
5652 return rec;
5653 }
5654 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5655 if (activity.pendingResults == null) {
5656 activity.pendingResults = new HashSet<>();
5657 }
5658 activity.pendingResults.add(rec.ref);
5659 }
5660 return rec;
5661 }
5662
Andrii Kulian52d255c2018-07-13 11:32:19 -07005663 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005664 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005665 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005666 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5667 mCurAppTimeTracker.start(resumedActivity.packageName);
5668 }
5669 }
5670
5671 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5672 if (mTracedResumedActivity != null) {
5673 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5674 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5675 }
5676 if (resumed != null) {
5677 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5678 constructResumedTraceName(resumed.packageName), 0);
5679 }
5680 mTracedResumedActivity = resumed;
5681 }
5682
5683 private String constructResumedTraceName(String packageName) {
5684 return "focused app: " + packageName;
5685 }
5686
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005687 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005688 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005689 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005690 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005691 // mainStack is null during startup.
5692 if (mainStack != null) {
5693 if (changes != 0 && starting == null) {
5694 // If the configuration changed, and the caller is not already
5695 // in the process of starting an activity, then find the top
5696 // activity to check if its configuration needs to change.
5697 starting = mainStack.topRunningActivityLocked();
5698 }
5699
5700 if (starting != null) {
5701 kept = starting.ensureActivityConfiguration(changes,
5702 false /* preserveWindow */);
5703 // And we need to make sure at this point that all other activities
5704 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005705 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005706 !PRESERVE_WINDOWS);
5707 }
5708 }
5709
5710 return kept;
5711 }
5712
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005713 void scheduleAppGcsLocked() {
5714 mH.post(() -> mAmInternal.scheduleAppGcs());
5715 }
5716
Wale Ogunwale53783742018-09-16 10:21:51 -07005717 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5718 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5719 }
5720
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005721 /**
5722 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5723 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5724 * on demand.
5725 */
5726 IPackageManager getPackageManager() {
5727 return AppGlobals.getPackageManager();
5728 }
5729
5730 PackageManagerInternal getPackageManagerInternalLocked() {
5731 if (mPmInternal == null) {
5732 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5733 }
5734 return mPmInternal;
5735 }
5736
Hai Zhangf4da9be2019-05-01 13:46:06 +08005737 PermissionPolicyInternal getPermissionPolicyInternal() {
5738 if (mPermissionPolicyInternal == null) {
5739 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5740 }
5741 return mPermissionPolicyInternal;
5742 }
5743
Wale Ogunwale008163e2018-07-23 23:11:08 -07005744 AppWarnings getAppWarningsLocked() {
5745 return mAppWarnings;
5746 }
5747
Wale Ogunwale214f3482018-10-04 11:00:47 -07005748 Intent getHomeIntent() {
5749 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5750 intent.setComponent(mTopComponent);
5751 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5752 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5753 intent.addCategory(Intent.CATEGORY_HOME);
5754 }
5755 return intent;
5756 }
5757
Chilun2ef71f72018-11-16 17:57:15 +08005758 /**
5759 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5760 * activities.
5761 *
5762 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5763 * component defined in config_secondaryHomeComponent.
5764 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5765 */
5766 Intent getSecondaryHomeIntent(String preferredPackage) {
5767 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005768 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5769 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5770 if (preferredPackage == null || useSystemProvidedLauncher) {
5771 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005772 final String secondaryHomeComponent = mContext.getResources().getString(
5773 com.android.internal.R.string.config_secondaryHomeComponent);
5774 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5775 } else {
5776 intent.setPackage(preferredPackage);
5777 }
5778 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5779 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5780 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5781 }
5782 return intent;
5783 }
5784
Wale Ogunwale214f3482018-10-04 11:00:47 -07005785 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5786 if (info == null) return null;
5787 ApplicationInfo newInfo = new ApplicationInfo(info);
5788 newInfo.initForUser(userId);
5789 return newInfo;
5790 }
5791
Wale Ogunwale9c103022018-10-18 07:44:54 -07005792 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005793 if (uid == SYSTEM_UID) {
5794 // The system gets to run in any process. If there are multiple processes with the same
5795 // uid, just pick the first (this should never happen).
5796 final SparseArray<WindowProcessController> procs =
5797 mProcessNames.getMap().get(processName);
5798 if (procs == null) return null;
5799 final int procCount = procs.size();
5800 for (int i = 0; i < procCount; i++) {
5801 final int procUid = procs.keyAt(i);
5802 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5803 // Don't use an app process or different user process for system component.
5804 continue;
5805 }
5806 return procs.valueAt(i);
5807 }
5808 }
5809
5810 return mProcessNames.get(processName, uid);
5811 }
5812
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005813 WindowProcessController getProcessController(IApplicationThread thread) {
5814 if (thread == null) {
5815 return null;
5816 }
5817
5818 final IBinder threadBinder = thread.asBinder();
5819 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5820 for (int i = pmap.size()-1; i >= 0; i--) {
5821 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5822 for (int j = procs.size() - 1; j >= 0; j--) {
5823 final WindowProcessController proc = procs.valueAt(j);
5824 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5825 return proc;
5826 }
5827 }
5828 }
5829
5830 return null;
5831 }
5832
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005833 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005834 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005835 if (proc == null) return null;
5836 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5837 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005838 }
5839 return null;
5840 }
5841
Riddle Hsua0536432019-02-16 00:38:59 +08005842 int getUidState(int uid) {
5843 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005844 }
5845
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005846 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005847 // A uid is considered to be foreground if it has a visible non-toast window.
5848 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005849 }
5850
Ricky Wai96f5c352019-04-10 18:40:17 +01005851 boolean isDeviceOwner(int uid) {
5852 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005853 }
5854
Ricky Wai96f5c352019-04-10 18:40:17 +01005855 void setDeviceOwnerUid(int uid) {
5856 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005857 }
5858
Wale Ogunwale9de19442018-10-18 19:05:03 -07005859 /**
5860 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5861 * the whitelist
5862 */
5863 String getPendingTempWhitelistTagForUidLocked(int uid) {
5864 return mPendingTempWhitelist.get(uid);
5865 }
5866
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005867 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5868 if (true || Build.IS_USER) {
5869 return;
5870 }
5871
5872 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5873 StrictMode.allowThreadDiskWrites();
5874 try {
5875 File tracesDir = new File("/data/anr");
5876 File tracesFile = null;
5877 try {
5878 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5879
5880 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005881 String timeString =
5882 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5883 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005884 sb.append(": ");
5885 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5886 sb.append(" since ");
5887 sb.append(msg);
5888 FileOutputStream fos = new FileOutputStream(tracesFile);
5889 fos.write(sb.toString().getBytes());
5890 if (app == null) {
5891 fos.write("\n*** No application process!".getBytes());
5892 }
5893 fos.close();
5894 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5895 } catch (IOException e) {
5896 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5897 return;
5898 }
5899
5900 if (app != null && app.getPid() > 0) {
5901 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5902 firstPids.add(app.getPid());
5903 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5904 }
5905
5906 File lastTracesFile = null;
5907 File curTracesFile = null;
5908 for (int i=9; i>=0; i--) {
5909 String name = String.format(Locale.US, "slow%02d.txt", i);
5910 curTracesFile = new File(tracesDir, name);
5911 if (curTracesFile.exists()) {
5912 if (lastTracesFile != null) {
5913 curTracesFile.renameTo(lastTracesFile);
5914 } else {
5915 curTracesFile.delete();
5916 }
5917 }
5918 lastTracesFile = curTracesFile;
5919 }
5920 tracesFile.renameTo(curTracesFile);
5921 } finally {
5922 StrictMode.setThreadPolicy(oldPolicy);
5923 }
5924 }
5925
Michal Karpinskida34cd42019-04-02 19:46:52 +01005926 boolean isAssociatedCompanionApp(int userId, int uid) {
5927 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5928 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005929 return false;
5930 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005931 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005932 }
5933
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005934 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005935 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005936
5937
Wale Ogunwale98875612018-10-12 07:53:02 -07005938 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5939 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005940
Riddle Hsud93a6c42018-11-29 21:50:06 +08005941 H(Looper looper) {
5942 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005943 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005944
5945 @Override
5946 public void handleMessage(Message msg) {
5947 switch (msg.what) {
5948 case REPORT_TIME_TRACKER_MSG: {
5949 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5950 tracker.deliverResult(mContext);
5951 } break;
5952 }
5953 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005954 }
5955
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005956 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005957 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005958
5959 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005960 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005961 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005962
5963 @Override
5964 public void handleMessage(Message msg) {
5965 switch (msg.what) {
5966 case DISMISS_DIALOG_UI_MSG: {
5967 final Dialog d = (Dialog) msg.obj;
5968 d.dismiss();
5969 break;
5970 }
5971 }
5972 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005973 }
5974
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005975 final class LocalService extends ActivityTaskManagerInternal {
5976 @Override
5977 public SleepToken acquireSleepToken(String tag, int displayId) {
5978 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005979 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005980 }
5981
5982 @Override
5983 public ComponentName getHomeActivityForUser(int userId) {
5984 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005985 final ActivityRecord homeActivity =
5986 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005987 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005988 }
5989 }
5990
5991 @Override
5992 public void onLocalVoiceInteractionStarted(IBinder activity,
5993 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5994 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005995 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005996 }
5997 }
5998
5999 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006000 public void notifyAppTransitionStarting(SparseIntArray reasons,
6001 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006002 synchronized (mGlobalLock) {
6003 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6004 reasons, timestamp);
6005 }
6006 }
6007
6008 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006009 public void notifySingleTaskDisplayDrawn(int displayId) {
6010 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6011 }
6012
6013 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006014 public void notifyAppTransitionFinished() {
6015 synchronized (mGlobalLock) {
6016 mStackSupervisor.notifyAppTransitionDone();
6017 }
6018 }
6019
6020 @Override
6021 public void notifyAppTransitionCancelled() {
6022 synchronized (mGlobalLock) {
6023 mStackSupervisor.notifyAppTransitionDone();
6024 }
6025 }
6026
6027 @Override
6028 public List<IBinder> getTopVisibleActivities() {
6029 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006030 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 }
6032 }
6033
6034 @Override
6035 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6036 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006037 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006038 }
6039 }
6040
6041 @Override
6042 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6043 Bundle bOptions) {
6044 Preconditions.checkNotNull(intents, "intents");
6045 final String[] resolvedTypes = new String[intents.length];
6046
6047 // UID of the package on user userId.
6048 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6049 // packageUid may not be initialized.
6050 int packageUid = 0;
6051 final long ident = Binder.clearCallingIdentity();
6052
6053 try {
6054 for (int i = 0; i < intents.length; i++) {
6055 resolvedTypes[i] =
6056 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6057 }
6058
6059 packageUid = AppGlobals.getPackageManager().getPackageUid(
6060 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6061 } catch (RemoteException e) {
6062 // Shouldn't happen.
6063 } finally {
6064 Binder.restoreCallingIdentity(ident);
6065 }
6066
Riddle Hsu591bf612019-02-14 17:55:31 +08006067 return getActivityStartController().startActivitiesInPackage(
6068 packageUid, packageName,
6069 intents, resolvedTypes, null /* resultTo */,
6070 SafeActivityOptions.fromBundle(bOptions), userId,
6071 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6072 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006073 }
6074
6075 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006076 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6077 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6078 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6079 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006080 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006081 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006082 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6083 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6084 userId, validateIncomingUser, originatingPendingIntent,
6085 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006086 }
6087 }
6088
6089 @Override
6090 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6091 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6092 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6093 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006094 PendingIntentRecord originatingPendingIntent,
6095 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006096 synchronized (mGlobalLock) {
6097 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6098 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6099 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006100 validateIncomingUser, originatingPendingIntent,
6101 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006102 }
6103 }
6104
6105 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6107 Intent intent, Bundle options, int userId) {
6108 return ActivityTaskManagerService.this.startActivityAsUser(
6109 caller, callerPacakge, intent,
6110 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6111 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6112 false /*validateIncomingUser*/);
6113 }
6114
6115 @Override
lumark588a3e82018-07-20 18:53:54 +08006116 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006117 synchronized (mGlobalLock) {
6118
6119 // We might change the visibilities here, so prepare an empty app transition which
6120 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006121 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006122 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006123 if (activityDisplay == null) {
6124 return;
6125 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006126 final DisplayContent dc = activityDisplay.mDisplayContent;
6127 final boolean wasTransitionSet =
6128 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006130 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006131 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006132 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006133
6134 // If there was a transition set already we don't want to interfere with it as we
6135 // might be starting it too early.
6136 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006137 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006138 }
6139 }
6140 if (callback != null) {
6141 callback.run();
6142 }
6143 }
6144
6145 @Override
6146 public void notifyKeyguardTrustedChanged() {
6147 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006148 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006149 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006150 }
6151 }
6152 }
6153
6154 /**
6155 * Called after virtual display Id is updated by
6156 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6157 * {@param vrVr2dDisplayId}.
6158 */
6159 @Override
6160 public void setVr2dDisplayId(int vr2dDisplayId) {
6161 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6162 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006163 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006164 }
6165 }
6166
6167 @Override
6168 public void setFocusedActivity(IBinder token) {
6169 synchronized (mGlobalLock) {
6170 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6171 if (r == null) {
6172 throw new IllegalArgumentException(
6173 "setFocusedActivity: No activity record matching token=" + token);
6174 }
Louis Chang19443452018-10-09 12:10:21 +08006175 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006176 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006177 }
6178 }
6179 }
6180
6181 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006182 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006183 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006184 }
6185
6186 @Override
6187 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006188 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006189 }
6190
6191 @Override
6192 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006193 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 }
6195
6196 @Override
6197 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6198 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6199 }
6200
6201 @Override
6202 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006203 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006204 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006205
6206 @Override
6207 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6208 synchronized (mGlobalLock) {
6209 mActiveVoiceInteractionServiceComponent = component;
6210 }
6211 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006212
6213 @Override
6214 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6215 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6216 return;
6217 }
6218 synchronized (mGlobalLock) {
6219 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6220 if (types == null) {
6221 if (uid < 0) {
6222 return;
6223 }
6224 types = new ArrayMap<>();
6225 mAllowAppSwitchUids.put(userId, types);
6226 }
6227 if (uid < 0) {
6228 types.remove(type);
6229 } else {
6230 types.put(type, uid);
6231 }
6232 }
6233 }
6234
6235 @Override
6236 public void onUserStopped(int userId) {
6237 synchronized (mGlobalLock) {
6238 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6239 mAllowAppSwitchUids.remove(userId);
6240 }
6241 }
6242
6243 @Override
6244 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6245 synchronized (mGlobalLock) {
6246 return ActivityTaskManagerService.this.isGetTasksAllowed(
6247 caller, callingPid, callingUid);
6248 }
6249 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006250
Riddle Hsua0536432019-02-16 00:38:59 +08006251 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006252 @Override
6253 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006254 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006255 mProcessNames.put(proc.mName, proc.mUid, proc);
6256 }
6257 }
6258
Riddle Hsua0536432019-02-16 00:38:59 +08006259 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006260 @Override
6261 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006262 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006263 mProcessNames.remove(name, uid);
6264 }
6265 }
6266
Riddle Hsua0536432019-02-16 00:38:59 +08006267 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006268 @Override
6269 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006270 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006271 if (proc == mHomeProcess) {
6272 mHomeProcess = null;
6273 }
6274 if (proc == mPreviousProcess) {
6275 mPreviousProcess = null;
6276 }
6277 }
6278 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006279
Riddle Hsua0536432019-02-16 00:38:59 +08006280 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006281 @Override
6282 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006283 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006284 return mTopProcessState;
6285 }
6286 }
6287
Riddle Hsua0536432019-02-16 00:38:59 +08006288 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006289 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006290 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006291 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006292 return proc == mHeavyWeightProcess;
6293 }
6294 }
6295
Riddle Hsua0536432019-02-16 00:38:59 +08006296 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006297 @Override
6298 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006299 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006300 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6301 }
6302 }
6303
6304 @Override
6305 public void finishHeavyWeightApp() {
6306 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006307 if (mHeavyWeightProcess != null) {
6308 mHeavyWeightProcess.finishActivities();
6309 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006310 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6311 mHeavyWeightProcess);
6312 }
6313 }
6314
Riddle Hsua0536432019-02-16 00:38:59 +08006315 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006316 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006317 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006318 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006319 return isSleepingLocked();
6320 }
6321 }
6322
6323 @Override
6324 public boolean isShuttingDown() {
6325 synchronized (mGlobalLock) {
6326 return mShuttingDown;
6327 }
6328 }
6329
6330 @Override
6331 public boolean shuttingDown(boolean booted, int timeout) {
6332 synchronized (mGlobalLock) {
6333 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006334 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006335 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006336 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006337 return mStackSupervisor.shutdownLocked(timeout);
6338 }
6339 }
6340
6341 @Override
6342 public void enableScreenAfterBoot(boolean booted) {
6343 synchronized (mGlobalLock) {
6344 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6345 SystemClock.uptimeMillis());
6346 mWindowManager.enableScreenAfterBoot();
6347 updateEventDispatchingLocked(booted);
6348 }
6349 }
6350
6351 @Override
6352 public boolean showStrictModeViolationDialog() {
6353 synchronized (mGlobalLock) {
6354 return mShowDialogs && !mSleeping && !mShuttingDown;
6355 }
6356 }
6357
6358 @Override
6359 public void showSystemReadyErrorDialogsIfNeeded() {
6360 synchronized (mGlobalLock) {
6361 try {
6362 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6363 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6364 + " data partition or your device will be unstable.");
6365 mUiHandler.post(() -> {
6366 if (mShowDialogs) {
6367 AlertDialog d = new BaseErrorDialog(mUiContext);
6368 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6369 d.setCancelable(false);
6370 d.setTitle(mUiContext.getText(R.string.android_system_label));
6371 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6372 d.setButton(DialogInterface.BUTTON_POSITIVE,
6373 mUiContext.getText(R.string.ok),
6374 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6375 d.show();
6376 }
6377 });
6378 }
6379 } catch (RemoteException e) {
6380 }
6381
6382 if (!Build.isBuildConsistent()) {
6383 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6384 mUiHandler.post(() -> {
6385 if (mShowDialogs) {
6386 AlertDialog d = new BaseErrorDialog(mUiContext);
6387 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6388 d.setCancelable(false);
6389 d.setTitle(mUiContext.getText(R.string.android_system_label));
6390 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6391 d.setButton(DialogInterface.BUTTON_POSITIVE,
6392 mUiContext.getText(R.string.ok),
6393 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6394 d.show();
6395 }
6396 });
6397 }
6398 }
6399 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006400
6401 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006402 public void onProcessMapped(int pid, WindowProcessController proc) {
6403 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006404 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006405 }
6406 }
6407
6408 @Override
6409 public void onProcessUnMapped(int pid) {
6410 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006411 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006412 }
6413 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006414
6415 @Override
6416 public void onPackageDataCleared(String name) {
6417 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006418 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006419 mAppWarnings.onPackageDataCleared(name);
6420 }
6421 }
6422
6423 @Override
6424 public void onPackageUninstalled(String name) {
6425 synchronized (mGlobalLock) {
6426 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006427 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006428 }
6429 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006430
6431 @Override
6432 public void onPackageAdded(String name, boolean replacing) {
6433 synchronized (mGlobalLock) {
6434 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6435 }
6436 }
6437
6438 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006439 public void onPackageReplaced(ApplicationInfo aInfo) {
6440 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006441 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006442 }
6443 }
6444
6445 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006446 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6447 synchronized (mGlobalLock) {
6448 return compatibilityInfoForPackageLocked(ai);
6449 }
6450 }
6451
Yunfan Chen75157d72018-07-27 14:47:21 +09006452 /**
6453 * Set the corresponding display information for the process global configuration. To be
6454 * called when we need to show IME on a different display.
6455 *
6456 * @param pid The process id associated with the IME window.
6457 * @param displayId The ID of the display showing the IME.
6458 */
6459 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006460 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006461 // Don't update process-level configuration for Multi-Client IME process since other
6462 // IMEs on other displays will also receive this configuration change due to IME
6463 // services use the same application config/context.
6464 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006465
Yunfan Chen75157d72018-07-27 14:47:21 +09006466 if (pid == MY_PID || pid < 0) {
6467 if (DEBUG_CONFIGURATION) {
6468 Slog.w(TAG,
6469 "Trying to update display configuration for system/invalid process.");
6470 }
6471 return;
6472 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006473 synchronized (mGlobalLock) {
6474 final ActivityDisplay activityDisplay =
6475 mRootActivityContainer.getActivityDisplay(displayId);
6476 if (activityDisplay == null) {
6477 // Call might come when display is not yet added or has been removed.
6478 if (DEBUG_CONFIGURATION) {
6479 Slog.w(TAG, "Trying to update display configuration for non-existing "
6480 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006481 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006482 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006483 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006484 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006485 if (process == null) {
6486 if (DEBUG_CONFIGURATION) {
6487 Slog.w(TAG, "Trying to update display configuration for invalid "
6488 + "process, pid=" + pid);
6489 }
6490 return;
6491 }
lumarkddc77fb2019-06-27 22:22:23 +08006492 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006493 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6494 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006495 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006496
6497 @Override
6498 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006499 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006500 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006501 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6502 if (r != null && r.getActivityStack() != null) {
6503 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6504 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006505 }
6506 }
6507 }
6508
6509 @Override
6510 public void clearPendingResultForActivity(IBinder activityToken,
6511 WeakReference<PendingIntentRecord> pir) {
6512 synchronized (mGlobalLock) {
6513 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6514 if (r != null && r.pendingResults != null) {
6515 r.pendingResults.remove(pir);
6516 }
6517 }
6518 }
6519
6520 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006521 public ActivityTokens getTopActivityForTask(int taskId) {
6522 synchronized (mGlobalLock) {
6523 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6524 if (taskRecord == null) {
6525 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6526 + " Requested task not found");
6527 return null;
6528 }
6529 final ActivityRecord activity = taskRecord.getTopActivity();
6530 if (activity == null) {
6531 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6532 + " Requested activity not found");
6533 return null;
6534 }
6535 if (!activity.attachedToProcess()) {
6536 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6537 + activity);
6538 return null;
6539 }
6540 return new ActivityTokens(activity.appToken, activity.assistToken,
6541 activity.app.getThread());
6542 }
6543 }
6544
6545 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006546 public IIntentSender getIntentSender(int type, String packageName,
6547 int callingUid, int userId, IBinder token, String resultWho,
6548 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6549 Bundle bOptions) {
6550 synchronized (mGlobalLock) {
6551 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6552 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6553 }
6554 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006555
6556 @Override
6557 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6558 synchronized (mGlobalLock) {
6559 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6560 if (r == null) {
6561 return null;
6562 }
6563 if (r.mServiceConnectionsHolder == null) {
6564 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6565 ActivityTaskManagerService.this, r);
6566 }
6567
6568 return r.mServiceConnectionsHolder;
6569 }
6570 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006571
6572 @Override
6573 public Intent getHomeIntent() {
6574 synchronized (mGlobalLock) {
6575 return ActivityTaskManagerService.this.getHomeIntent();
6576 }
6577 }
6578
6579 @Override
6580 public boolean startHomeActivity(int userId, String reason) {
6581 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006582 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006583 }
6584 }
6585
6586 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006587 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006588 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006589 synchronized (mGlobalLock) {
6590 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006591 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006592 }
Chilun8b1f1be2019-03-13 17:14:36 +08006593 }
6594
6595 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006596 public boolean startHomeOnAllDisplays(int userId, String reason) {
6597 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006598 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006599 }
6600 }
6601
Riddle Hsua0536432019-02-16 00:38:59 +08006602 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006603 @Override
6604 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006605 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006606 if (mFactoryTest == FACTORY_TEST_OFF) {
6607 return false;
6608 }
6609 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6610 && wpc.mName.equals(mTopComponent.getPackageName())) {
6611 return true;
6612 }
6613 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6614 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6615 }
6616 }
6617
6618 @Override
6619 public void updateTopComponentForFactoryTest() {
6620 synchronized (mGlobalLock) {
6621 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6622 return;
6623 }
6624 final ResolveInfo ri = mContext.getPackageManager()
6625 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6626 final CharSequence errorMsg;
6627 if (ri != null) {
6628 final ActivityInfo ai = ri.activityInfo;
6629 final ApplicationInfo app = ai.applicationInfo;
6630 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6631 mTopAction = Intent.ACTION_FACTORY_TEST;
6632 mTopData = null;
6633 mTopComponent = new ComponentName(app.packageName, ai.name);
6634 errorMsg = null;
6635 } else {
6636 errorMsg = mContext.getResources().getText(
6637 com.android.internal.R.string.factorytest_not_system);
6638 }
6639 } else {
6640 errorMsg = mContext.getResources().getText(
6641 com.android.internal.R.string.factorytest_no_action);
6642 }
6643 if (errorMsg == null) {
6644 return;
6645 }
6646
6647 mTopAction = null;
6648 mTopData = null;
6649 mTopComponent = null;
6650 mUiHandler.post(() -> {
6651 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6652 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006653 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006654 });
6655 }
6656 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006657
Riddle Hsua0536432019-02-16 00:38:59 +08006658 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006659 @Override
6660 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6661 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006662 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006663 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006664 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006665
6666 wpc.clearRecentTasks();
6667 wpc.clearActivities();
6668
6669 if (wpc.isInstrumenting()) {
6670 finishInstrumentationCallback.run();
6671 }
6672
Jorim Jaggid0752812018-10-16 16:07:20 +02006673 if (!restarting && hasVisibleActivities) {
6674 mWindowManager.deferSurfaceLayout();
6675 try {
6676 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6677 // If there was nothing to resume, and we are not already restarting
6678 // this process, but there is a visible activity that is hosted by the
6679 // process...then make sure all visible activities are running, taking
6680 // care of restarting this process.
6681 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6682 !PRESERVE_WINDOWS);
6683 }
6684 } finally {
6685 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006686 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006687 }
6688 }
6689 }
6690
6691 @Override
6692 public void closeSystemDialogs(String reason) {
6693 enforceNotIsolatedCaller("closeSystemDialogs");
6694
6695 final int pid = Binder.getCallingPid();
6696 final int uid = Binder.getCallingUid();
6697 final long origId = Binder.clearCallingIdentity();
6698 try {
6699 synchronized (mGlobalLock) {
6700 // Only allow this from foreground processes, so that background
6701 // applications can't abuse it to prevent system UI from being shown.
6702 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006703 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006704 if (!proc.isPerceptible()) {
6705 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6706 + " from background process " + proc);
6707 return;
6708 }
6709 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006710 mWindowManager.closeSystemDialogs(reason);
6711
Wale Ogunwaled32da472018-11-16 07:19:28 -08006712 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006714 // Call into AM outside the synchronized block.
6715 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716 } finally {
6717 Binder.restoreCallingIdentity(origId);
6718 }
6719 }
6720
6721 @Override
6722 public void cleanupDisabledPackageComponents(
6723 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6724 synchronized (mGlobalLock) {
6725 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006726 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006727 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006728 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729 mStackSupervisor.scheduleIdleLocked();
6730 }
6731
6732 // Clean-up disabled tasks
6733 getRecentTasks().cleanupDisabledPackageTasksLocked(
6734 packageName, disabledClasses, userId);
6735 }
6736 }
6737
6738 @Override
6739 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6740 int userId) {
6741 synchronized (mGlobalLock) {
6742
6743 boolean didSomething =
6744 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006745 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006746 null, doit, evenPersistent, userId);
6747 return didSomething;
6748 }
6749 }
6750
6751 @Override
6752 public void resumeTopActivities(boolean scheduleIdle) {
6753 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006754 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006755 if (scheduleIdle) {
6756 mStackSupervisor.scheduleIdleLocked();
6757 }
6758 }
6759 }
6760
Riddle Hsua0536432019-02-16 00:38:59 +08006761 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006762 @Override
6763 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006764 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006765 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6766 }
6767 }
6768
Riddle Hsua0536432019-02-16 00:38:59 +08006769 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006770 @Override
6771 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006772 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006773 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006774 }
6775 }
6776
6777 @Override
6778 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6779 try {
6780 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6781 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6782 }
6783 } catch (RemoteException ex) {
6784 throw new SecurityException("Fail to check is caller a privileged app", ex);
6785 }
6786
6787 synchronized (mGlobalLock) {
6788 final long ident = Binder.clearCallingIdentity();
6789 try {
6790 if (mAmInternal.shouldConfirmCredentials(userId)) {
6791 if (mKeyguardController.isKeyguardLocked()) {
6792 // Showing launcher to avoid user entering credential twice.
6793 startHomeActivity(currentUserId, "notifyLockedProfile");
6794 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006795 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 }
6797 } finally {
6798 Binder.restoreCallingIdentity(ident);
6799 }
6800 }
6801 }
6802
6803 @Override
6804 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6805 mAmInternal.enforceCallingPermission(
6806 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6807
6808 synchronized (mGlobalLock) {
6809 final long ident = Binder.clearCallingIdentity();
6810 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006811 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6812 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006813 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6815 UserHandle.CURRENT);
6816 } finally {
6817 Binder.restoreCallingIdentity(ident);
6818 }
6819 }
6820 }
6821
6822 @Override
6823 public void writeActivitiesToProto(ProtoOutputStream proto) {
6824 synchronized (mGlobalLock) {
6825 // The output proto of "activity --proto activities"
6826 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006827 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006828 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6829 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
6831 }
6832
6833 @Override
6834 public void saveANRState(String reason) {
6835 synchronized (mGlobalLock) {
6836 final StringWriter sw = new StringWriter();
6837 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6838 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6839 if (reason != null) {
6840 pw.println(" Reason: " + reason);
6841 }
6842 pw.println();
6843 getActivityStartController().dump(pw, " ", null);
6844 pw.println();
6845 pw.println("-------------------------------------------------------------------------------");
6846 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6847 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6848 "" /* header */);
6849 pw.println();
6850 pw.close();
6851
6852 mLastANRState = sw.toString();
6853 }
6854 }
6855
6856 @Override
6857 public void clearSavedANRState() {
6858 synchronized (mGlobalLock) {
6859 mLastANRState = null;
6860 }
6861 }
6862
6863 @Override
6864 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6865 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6866 synchronized (mGlobalLock) {
6867 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6868 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6869 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6870 dumpLastANRLocked(pw);
6871 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6872 dumpLastANRTracesLocked(pw);
6873 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6874 dumpActivityStarterLocked(pw, dumpPackage);
6875 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6876 dumpActivityContainersLocked(pw);
6877 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6878 if (getRecentTasks() != null) {
6879 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6880 }
6881 }
6882 }
6883 }
6884
6885 @Override
6886 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6887 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6888 int wakefulness) {
6889 synchronized (mGlobalLock) {
6890 if (mHomeProcess != null && (dumpPackage == null
6891 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6892 if (needSep) {
6893 pw.println();
6894 needSep = false;
6895 }
6896 pw.println(" mHomeProcess: " + mHomeProcess);
6897 }
6898 if (mPreviousProcess != null && (dumpPackage == null
6899 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6900 if (needSep) {
6901 pw.println();
6902 needSep = false;
6903 }
6904 pw.println(" mPreviousProcess: " + mPreviousProcess);
6905 }
6906 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6907 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6908 StringBuilder sb = new StringBuilder(128);
6909 sb.append(" mPreviousProcessVisibleTime: ");
6910 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6911 pw.println(sb);
6912 }
6913 if (mHeavyWeightProcess != null && (dumpPackage == null
6914 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6915 if (needSep) {
6916 pw.println();
6917 needSep = false;
6918 }
6919 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6920 }
6921 if (dumpPackage == null) {
6922 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006923 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006924 }
6925 if (dumpAll) {
6926 if (dumpPackage == null) {
6927 pw.println(" mConfigWillChange: "
6928 + getTopDisplayFocusedStack().mConfigWillChange);
6929 }
6930 if (mCompatModePackages.getPackages().size() > 0) {
6931 boolean printed = false;
6932 for (Map.Entry<String, Integer> entry
6933 : mCompatModePackages.getPackages().entrySet()) {
6934 String pkg = entry.getKey();
6935 int mode = entry.getValue();
6936 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6937 continue;
6938 }
6939 if (!printed) {
6940 pw.println(" mScreenCompatPackages:");
6941 printed = true;
6942 }
6943 pw.println(" " + pkg + ": " + mode);
6944 }
6945 }
6946 }
6947
6948 if (dumpPackage == null) {
6949 pw.println(" mWakefulness="
6950 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006951 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006952 if (mRunningVoice != null) {
6953 pw.println(" mRunningVoice=" + mRunningVoice);
6954 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6955 }
6956 pw.println(" mSleeping=" + mSleeping);
6957 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6958 pw.println(" mVrController=" + mVrController);
6959 }
6960 if (mCurAppTimeTracker != null) {
6961 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6962 }
6963 if (mAllowAppSwitchUids.size() > 0) {
6964 boolean printed = false;
6965 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6966 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6967 for (int j = 0; j < types.size(); j++) {
6968 if (dumpPackage == null ||
6969 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6970 if (needSep) {
6971 pw.println();
6972 needSep = false;
6973 }
6974 if (!printed) {
6975 pw.println(" mAllowAppSwitchUids:");
6976 printed = true;
6977 }
6978 pw.print(" User ");
6979 pw.print(mAllowAppSwitchUids.keyAt(i));
6980 pw.print(": Type ");
6981 pw.print(types.keyAt(j));
6982 pw.print(" = ");
6983 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6984 pw.println();
6985 }
6986 }
6987 }
6988 }
6989 if (dumpPackage == null) {
6990 if (mController != null) {
6991 pw.println(" mController=" + mController
6992 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6993 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006994 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6995 pw.println(" mLaunchingActivityWakeLock="
6996 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006997 }
6998
6999 return needSep;
7000 }
7001 }
7002
7003 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007004 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7005 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007006 synchronized (mGlobalLock) {
7007 if (dumpPackage == null) {
7008 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7009 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007010 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7011 if (mRunningVoice != null) {
7012 final long vrToken = proto.start(
7013 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7014 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7015 mRunningVoice.toString());
7016 mVoiceWakeLock.writeToProto(
7017 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7018 proto.end(vrToken);
7019 }
7020 mVrController.writeToProto(proto,
7021 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007022 if (mController != null) {
7023 final long token = proto.start(CONTROLLER);
7024 proto.write(CONTROLLER, mController.toString());
7025 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7026 proto.end(token);
7027 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007028 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7029 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7030 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007031 }
7032
7033 if (mHomeProcess != null && (dumpPackage == null
7034 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007035 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007036 }
7037
7038 if (mPreviousProcess != null && (dumpPackage == null
7039 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007040 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007041 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7042 }
7043
7044 if (mHeavyWeightProcess != null && (dumpPackage == null
7045 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007046 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007047 }
7048
7049 for (Map.Entry<String, Integer> entry
7050 : mCompatModePackages.getPackages().entrySet()) {
7051 String pkg = entry.getKey();
7052 int mode = entry.getValue();
7053 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7054 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7055 proto.write(PACKAGE, pkg);
7056 proto.write(MODE, mode);
7057 proto.end(compatToken);
7058 }
7059 }
7060
7061 if (mCurAppTimeTracker != null) {
7062 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7063 }
7064
7065 }
7066 }
7067
7068 @Override
7069 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7070 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7071 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007072 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7073 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007074 }
7075
7076 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007077 public void dumpForOom(PrintWriter pw) {
7078 synchronized (mGlobalLock) {
7079 pw.println(" mHomeProcess: " + mHomeProcess);
7080 pw.println(" mPreviousProcess: " + mPreviousProcess);
7081 if (mHeavyWeightProcess != null) {
7082 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7083 }
7084 }
7085 }
7086
7087 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 public boolean canGcNow() {
7089 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007090 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007091 }
7092 }
7093
Riddle Hsua0536432019-02-16 00:38:59 +08007094 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007095 @Override
7096 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007097 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007098 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007099 return top != null ? top.app : null;
7100 }
7101 }
7102
Riddle Hsua0536432019-02-16 00:38:59 +08007103 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 @Override
7105 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007106 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007107 if (mRootActivityContainer != null) {
7108 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 }
7110 }
7111 }
7112
7113 @Override
7114 public void scheduleDestroyAllActivities(String reason) {
7115 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007116 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007117 }
7118 }
7119
7120 @Override
7121 public void removeUser(int userId) {
7122 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007123 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007124 }
7125 }
7126
7127 @Override
7128 public boolean switchUser(int userId, UserState userState) {
7129 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007130 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007131 }
7132 }
7133
7134 @Override
7135 public void onHandleAppCrash(WindowProcessController wpc) {
7136 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007137 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007138 }
7139 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007140
7141 @Override
7142 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7143 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007144 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007145 }
7146 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007147
Riddle Hsua0536432019-02-16 00:38:59 +08007148 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007149 @Override
7150 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007151 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007152 }
7153
Riddle Hsua0536432019-02-16 00:38:59 +08007154 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007155 @Override
7156 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007157 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007158 }
7159
Riddle Hsua0536432019-02-16 00:38:59 +08007160 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007161 @Override
7162 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007163 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007164 }
7165
Riddle Hsua0536432019-02-16 00:38:59 +08007166 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007167 @Override
7168 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007169 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007170 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007171
7172 @Override
7173 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007174 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007175 mPendingTempWhitelist.put(uid, tag);
7176 }
7177 }
7178
7179 @Override
7180 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007181 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007182 mPendingTempWhitelist.remove(uid);
7183 }
7184 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007185
7186 @Override
7187 public boolean handleAppCrashInActivityController(String processName, int pid,
7188 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7189 Runnable killCrashingAppCallback) {
7190 synchronized (mGlobalLock) {
7191 if (mController == null) {
7192 return false;
7193 }
7194
7195 try {
7196 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7197 stackTrace)) {
7198 killCrashingAppCallback.run();
7199 return true;
7200 }
7201 } catch (RemoteException e) {
7202 mController = null;
7203 Watchdog.getInstance().setActivityController(null);
7204 }
7205 return false;
7206 }
7207 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007208
7209 @Override
7210 public void removeRecentTasksByPackageName(String packageName, int userId) {
7211 synchronized (mGlobalLock) {
7212 mRecentTasks.removeTasksByPackageName(packageName, userId);
7213 }
7214 }
7215
7216 @Override
7217 public void cleanupRecentTasksForUser(int userId) {
7218 synchronized (mGlobalLock) {
7219 mRecentTasks.cleanupLocked(userId);
7220 }
7221 }
7222
7223 @Override
7224 public void loadRecentTasksForUser(int userId) {
7225 synchronized (mGlobalLock) {
7226 mRecentTasks.loadUserRecentsLocked(userId);
7227 }
7228 }
7229
7230 @Override
7231 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7232 synchronized (mGlobalLock) {
7233 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7234 }
7235 }
7236
7237 @Override
7238 public void flushRecentTasks() {
7239 mRecentTasks.flush();
7240 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007241
7242 @Override
7243 public WindowProcessController getHomeProcess() {
7244 synchronized (mGlobalLock) {
7245 return mHomeProcess;
7246 }
7247 }
7248
7249 @Override
7250 public WindowProcessController getPreviousProcess() {
7251 synchronized (mGlobalLock) {
7252 return mPreviousProcess;
7253 }
7254 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007255
7256 @Override
7257 public void clearLockedTasks(String reason) {
7258 synchronized (mGlobalLock) {
7259 getLockTaskController().clearLockedTasks(reason);
7260 }
7261 }
7262
7263 @Override
7264 public void updateUserConfiguration() {
7265 synchronized (mGlobalLock) {
7266 final Configuration configuration = new Configuration(getGlobalConfiguration());
7267 final int currentUserId = mAmInternal.getCurrentUserId();
7268 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7269 configuration, currentUserId, Settings.System.canWrite(mContext));
7270 updateConfigurationLocked(configuration, null /* starting */,
7271 false /* initLocale */, false /* persistent */, currentUserId,
7272 false /* deferResume */);
7273 }
7274 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007275
7276 @Override
7277 public boolean canShowErrorDialogs() {
7278 synchronized (mGlobalLock) {
7279 return mShowDialogs && !mSleeping && !mShuttingDown
7280 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7281 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7282 mAmInternal.getCurrentUserId())
7283 && !(UserManager.isDeviceInDemoMode(mContext)
7284 && mAmInternal.getCurrentUser().isDemo());
7285 }
7286 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007287
7288 @Override
7289 public void setProfileApp(String profileApp) {
7290 synchronized (mGlobalLock) {
7291 mProfileApp = profileApp;
7292 }
7293 }
7294
7295 @Override
7296 public void setProfileProc(WindowProcessController wpc) {
7297 synchronized (mGlobalLock) {
7298 mProfileProc = wpc;
7299 }
7300 }
7301
7302 @Override
7303 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7304 synchronized (mGlobalLock) {
7305 mProfilerInfo = profilerInfo;
7306 }
7307 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007308
7309 @Override
7310 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7311 synchronized (mGlobalLock) {
7312 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7313 }
7314 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007315
7316 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007317 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7318 boolean reducedResolution) {
7319 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7320 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007321 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007322
7323 @Override
7324 public boolean isUidForeground(int uid) {
7325 synchronized (mGlobalLock) {
7326 return ActivityTaskManagerService.this.isUidForeground(uid);
7327 }
7328 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007329
7330 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007331 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007332 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007333 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007334 }
7335 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007336
7337 @Override
7338 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007339 // Translate package names into UIDs
7340 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007341 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007342 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7343 if (uid >= 0) {
7344 result.add(uid);
7345 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007346 }
7347 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007348 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007349 }
7350 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007351 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007352}