blob: d97f0f5041a474a5df932695be75293ff06d36ba [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
Nicholas Sauer0259e532019-08-30 08:24:55 -070022import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070025import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070026import static android.Manifest.permission.READ_FRAME_BUFFER;
27import static android.Manifest.permission.REMOVE_TASKS;
28import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070029import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070030import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070031import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070032import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070033import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070034import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
35import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
37import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
39import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070041import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070043import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
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;
Andrii Kulianf49a58c2019-08-14 17:34:27 -070087import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
88import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100138import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700139import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700140import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700141import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700142import android.app.IApplicationThread;
143import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400145import android.app.IRequestFinishCallback;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700146import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700147import android.app.Notification;
148import android.app.NotificationManager;
149import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.PictureInPictureParams;
151import android.app.ProfilerInfo;
152import android.app.RemoteAction;
153import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700154import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700155import android.app.admin.DevicePolicyCache;
156import android.app.assist.AssistContent;
157import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700158import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.content.ActivityNotFoundException;
160import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700161import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700162import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700163import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700164import android.content.IIntentSender;
165import android.content.Intent;
166import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700167import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900168import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700171import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.pm.ParceledListSlice;
173import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700174import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700176import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700177import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.graphics.Bitmap;
179import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700181import android.metrics.LogMaker;
182import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700183import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700186import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700187import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700188import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700190import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700191import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800192import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100197import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700200import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.SystemClock;
202import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700205import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.UserManager;
207import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700208import android.os.storage.IStorageManager;
209import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700210import android.provider.Settings;
211import android.service.voice.IVoiceInteractionSession;
212import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900213import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700214import android.telecom.TelecomManager;
215import android.text.TextUtils;
Neil Fuller97746812019-08-19 14:20:50 +0100216import android.text.format.TimeMigrationUtils;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700217import android.util.ArrayMap;
218import android.util.EventLog;
219import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700220import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700222import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700224import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700225import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700226import android.view.IRecentsAnimationRunner;
227import android.view.RemoteAnimationAdapter;
228import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700229import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700230
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700232import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700234import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700236import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700239import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700241import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700242import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700243import com.android.internal.policy.IKeyguardDismissCallback;
244import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700247import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700248import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700249import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Tarandeep Singh07b318b2019-07-17 11:12:04 -0700266import com.android.server.inputmethod.InputMethodSystemProperty;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800268import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100315 // How long we permit background activity starts after an activity in the process
316 // started or finished.
317 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318
Wale Ogunwale98875612018-10-12 07:53:02 -0700319 /** Used to indicate that an app transition should be animated. */
320 static final boolean ANIMATE = true;
321
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700322 /** Hardware-reported OpenGLES version. */
323 final int GL_ES_VERSION;
324
Wale Ogunwale31913b52018-10-13 08:29:31 -0700325 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
326 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
327 public static final String DUMP_LASTANR_CMD = "lastanr" ;
328 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
329 public static final String DUMP_STARTER_CMD = "starter" ;
330 public static final String DUMP_CONTAINERS_CMD = "containers" ;
331 public static final String DUMP_RECENTS_CMD = "recents" ;
332 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
333
Wale Ogunwale64258362018-10-16 15:13:37 -0700334 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
335 public static final int RELAUNCH_REASON_NONE = 0;
336 /** This activity is being relaunched due to windowing mode change. */
337 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
338 /** This activity is being relaunched due to a free-resize operation. */
339 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
340
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700341 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700342
Wale Ogunwalef6733932018-06-27 05:14:34 -0700343 /**
344 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
345 * change at runtime. Use mContext for non-UI purposes.
346 */
347 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700349 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700352 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700353 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800354 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800355 @VisibleForTesting
356 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 PowerManagerInternal mPowerManagerInternal;
358 private UsageStatsManagerInternal mUsageStatsInternal;
359
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700360 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 IntentFirewall mIntentFirewall;
362
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700363 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800364 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 /**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700366 * It is the same instance as {@link #mGlobalLock}, just declared as a type that the
Riddle Hsud7088f82019-01-30 13:04:50 +0800367 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
368 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
369 *
370 * @see WindowManagerThreadPriorityBooster
371 */
372 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700373 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800374 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700375 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700376 private UserManagerService mUserManager;
377 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700378 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800379 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700380 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** All processes currently running that might have a window organized by name. */
382 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100383 /** All processes we currently have running mapped by pid and uid */
384 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** This is the process holding what we currently consider to be the "home" activity. */
386 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700387 /** The currently running heavy-weight process, if any. */
388 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700389 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /**
391 * This is the process holding the activity the user last visited that is in a different process
392 * from the one they are currently in.
393 */
394 WindowProcessController mPreviousProcess;
395 /** The time at which the previous process was last visible. */
396 long mPreviousProcessVisibleTime;
397
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700398 /** List of intents that were used to start the most recent tasks. */
399 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700400 /** State of external calls telling us if the device is awake or asleep. */
401 private boolean mKeyguardShown = false;
402
403 // Wrapper around VoiceInteractionServiceManager
404 private AssistUtils mAssistUtils;
405
406 // VoiceInteraction session ID that changes for each new request except when
407 // being called for multi-window assist in a single session.
408 private int mViSessionId = 1000;
409
410 // How long to wait in getAssistContextExtras for the activity and foreground services
411 // to respond with the result.
412 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
413
414 // How long top wait when going through the modern assist (which doesn't need to block
415 // on getting this result before starting to launch its UI).
416 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
417
418 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
419 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
420
Alison Cichowlas3e340502018-08-07 17:15:01 -0400421 // Permission tokens are used to temporarily granted a trusted app the ability to call
422 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
423 // showing any appropriate error messages to the user.
424 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
425 10 * MINUTE_IN_MILLIS;
426
427 // How long before the service actually expires a token. This is slightly longer than
428 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
429 // expiration exception.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
431 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
432
433 // How long the service will remember expired tokens, for the purpose of providing error
434 // messaging when a client uses an expired token.
435 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
436 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
437
438 // Activity tokens of system activities that are delegating their call to
439 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
440 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
441
442 // Permission tokens that have expired, but we remember for error reporting.
443 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
444
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700445 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
446
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447 // Keeps track of the active voice interaction service component, notified from
448 // VoiceInteractionManagerService
449 ComponentName mActiveVoiceInteractionServiceComponent;
450
Michal Karpinskida34cd42019-04-02 19:46:52 +0100451 // A map userId and all its companion app uids
452 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000453
Wale Ogunwalee2172292018-10-25 10:11:10 -0700454 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700455 KeyguardController mKeyguardController;
456 private final ClientLifecycleManager mLifecycleManager;
457 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700458 /** The controller for all operations related to locktask. */
459 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700460 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700461
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700462 boolean mSuppressResizeConfigChanges;
463
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700464 final UpdateConfigurationResult mTmpUpdateConfigurationResult =
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 new UpdateConfigurationResult();
466
467 static final class UpdateConfigurationResult {
468 // Configuration changes that were updated.
469 int changes;
470 // If the activity was relaunched to match the new configuration.
471 boolean activityRelaunched;
472
473 void reset() {
474 changes = 0;
475 activityRelaunched = false;
476 }
477 }
478
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700479 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 private int mConfigurationSeq;
481 // To cache the list of supported system locales
482 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700483
484 /**
485 * Temp object used when global and/or display override configuration is updated. It is also
486 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
487 * anyone...
488 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700489 private Configuration mTempConfig = new Configuration();
490
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 /** Temporary to avoid allocations. */
492 final StringBuilder mStringBuilder = new StringBuilder(256);
493
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700494 // Amount of time after a call to stopAppSwitches() during which we will
495 // prevent further untrusted switches from happening.
496 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
497
498 /**
499 * The time at which we will allow normal application switches again,
500 * after a call to {@link #stopAppSwitches()}.
501 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700502 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700503 /**
504 * This is set to true after the first switch after mAppSwitchesAllowedTime
505 * is set; any switches after that will clear the time.
506 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700507 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508
Ricky Wai906af482019-06-03 17:25:28 +0100509 /**
510 * Last stop app switches time, apps finished before this time cannot start background activity
511 * even if they are in grace period.
512 */
513 private long mLastStopAppSwitchesTime;
514
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 IActivityController mController = null;
516 boolean mControllerIsAMonkey = false;
517
Wale Ogunwale214f3482018-10-04 11:00:47 -0700518 final int mFactoryTest;
519
520 /** Used to control how we initialize the service. */
521 ComponentName mTopComponent;
522 String mTopAction = Intent.ACTION_MAIN;
523 String mTopData;
524
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800525 /** Profiling app information. */
526 String mProfileApp = null;
527 WindowProcessController mProfileProc = null;
528 ProfilerInfo mProfilerInfo = null;
529
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700531 * Dump of the activity state at the time of the last ANR. Cleared after
532 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
533 */
534 String mLastANRState;
535
536 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700537 * Used to retain an update lock when the foreground activity is in
538 * immersive mode.
539 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700540 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700541
542 /**
543 * Packages that are being allowed to perform unrestricted app switches. Mapping is
544 * User -> Type -> uid.
545 */
546 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
547
548 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 private int mThumbnailWidth;
550 private int mThumbnailHeight;
551 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700552
553 /**
554 * Flag that indicates if multi-window is enabled.
555 *
556 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
557 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
558 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
559 * At least one of the forms of multi-window must be enabled in order for this flag to be
560 * initialized to 'true'.
561 *
562 * @see #mSupportsSplitScreenMultiWindow
563 * @see #mSupportsFreeformWindowManagement
564 * @see #mSupportsPictureInPicture
565 * @see #mSupportsMultiDisplay
566 */
567 boolean mSupportsMultiWindow;
568 boolean mSupportsSplitScreenMultiWindow;
569 boolean mSupportsFreeformWindowManagement;
570 boolean mSupportsPictureInPicture;
571 boolean mSupportsMultiDisplay;
572 boolean mForceResizableActivities;
573
574 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
575
576 // VR Vr2d Display Id.
577 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700578
Wale Ogunwalef6733932018-06-27 05:14:34 -0700579 /**
580 * Set while we are wanting to sleep, to prevent any
581 * activities from being started/resumed.
582 *
583 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
584 *
585 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
586 * while in the sleep state until there is a pending transition out of sleep, in which case
587 * mSleeping is set to false, and remains false while awake.
588 *
589 * Whether mSleeping can quickly toggled between true/false without the device actually
590 * display changing states is undefined.
591 */
592 private boolean mSleeping = false;
593
594 /**
595 * The process state used for processes that are running the top activities.
596 * This changes between TOP and TOP_SLEEPING to following mSleeping.
597 */
598 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
599
600 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
601 // automatically. Important for devices without direct input devices.
602 private boolean mShowDialogs = true;
603
604 /** Set if we are shutting down the system, similar to sleeping. */
605 boolean mShuttingDown = false;
606
607 /**
608 * We want to hold a wake lock while running a voice interaction session, since
609 * this may happen with the screen off and we need to keep the CPU running to
610 * be able to continue to interact with the user.
611 */
612 PowerManager.WakeLock mVoiceWakeLock;
613
614 /**
615 * Set while we are running a voice interaction. This overrides sleeping while it is active.
616 */
617 IVoiceInteractionSession mRunningVoice;
618
619 /**
620 * The last resumed activity. This is identical to the current resumed activity most
621 * of the time but could be different when we're pausing one activity before we resume
622 * another activity.
623 */
624 ActivityRecord mLastResumedActivity;
625
626 /**
627 * The activity that is currently being traced as the active resumed activity.
628 *
629 * @see #updateResumedAppTrace
630 */
631 private @Nullable ActivityRecord mTracedResumedActivity;
632
633 /** If non-null, we are tracking the time the user spends in the currently focused app. */
634 AppTimeTracker mCurAppTimeTracker;
635
Shivam Agrawal1d3db652019-07-01 15:26:11 -0700636 AppWarnings mAppWarnings;
Wale Ogunwale008163e2018-07-23 23:11:08 -0700637
Wale Ogunwale53783742018-09-16 10:21:51 -0700638 /**
639 * Packages that the user has asked to have run in screen size
640 * compatibility mode instead of filling the screen.
641 */
642 CompatModePackages mCompatModePackages;
643
Wale Ogunwalef6733932018-06-27 05:14:34 -0700644 private FontScaleSettingObserver mFontScaleSettingObserver;
645
Ricky Wai96f5c352019-04-10 18:40:17 +0100646 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000647
Wale Ogunwalef6733932018-06-27 05:14:34 -0700648 private final class FontScaleSettingObserver extends ContentObserver {
649 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
650 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
651
652 public FontScaleSettingObserver() {
653 super(mH);
654 final ContentResolver resolver = mContext.getContentResolver();
655 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
656 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
657 UserHandle.USER_ALL);
658 }
659
660 @Override
661 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
662 if (mFontScaleUri.equals(uri)) {
663 updateFontScaleIfNeeded(userId);
664 } else if (mHideErrorDialogsUri.equals(uri)) {
665 synchronized (mGlobalLock) {
666 updateShouldShowDialogsLocked(getGlobalConfiguration());
667 }
668 }
669 }
670 }
671
Riddle Hsua0536432019-02-16 00:38:59 +0800672 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
673 @Target(ElementType.METHOD)
674 @Retention(RetentionPolicy.SOURCE)
675 @interface HotPath {
676 int NONE = 0;
677 int OOM_ADJUSTMENT = 1;
678 int LRU_UPDATE = 2;
679 int PROCESS_CHANGE = 3;
680 int caller() default NONE;
681 }
682
Charles Chen8d98dd22018-12-26 17:36:54 +0800683 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
684 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700685 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700686 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700687 mSystemThread = ActivityThread.currentActivityThread();
688 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700689 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800690 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700691 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700692 }
693
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700694 public void onSystemReady() {
695 synchronized (mGlobalLock) {
696 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
697 PackageManager.FEATURE_CANT_SAVE_STATE);
698 mAssistUtils = new AssistUtils(mContext);
699 mVrController.onSystemReady();
700 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700701 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700702 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700703 }
704
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700705 public void onInitPowerManagement() {
706 synchronized (mGlobalLock) {
707 mStackSupervisor.initPowerManagement();
708 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
709 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
710 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
711 mVoiceWakeLock.setReferenceCounted(false);
712 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700713 }
714
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700715 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700716 mFontScaleSettingObserver = new FontScaleSettingObserver();
717 }
718
Wale Ogunwale59507092018-10-29 09:00:30 -0700719 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700720 final boolean freeformWindowManagement =
721 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
722 || Settings.Global.getInt(
723 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
724
725 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
726 final boolean supportsPictureInPicture = supportsMultiWindow &&
727 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
728 final boolean supportsSplitScreenMultiWindow =
729 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
730 final boolean supportsMultiDisplay = mContext.getPackageManager()
731 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700732 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
733 final boolean forceResizable = Settings.Global.getInt(
734 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
735
736 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900737 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700738
739 final Configuration configuration = new Configuration();
740 Settings.System.getConfiguration(resolver, configuration);
741 if (forceRtl) {
742 // This will take care of setting the correct layout direction flags
743 configuration.setLayoutDirection(configuration.locale);
744 }
745
746 synchronized (mGlobalLock) {
747 mForceResizableActivities = forceResizable;
748 final boolean multiWindowFormEnabled = freeformWindowManagement
749 || supportsSplitScreenMultiWindow
750 || supportsPictureInPicture
751 || supportsMultiDisplay;
752 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
753 mSupportsMultiWindow = true;
754 mSupportsFreeformWindowManagement = freeformWindowManagement;
755 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
756 mSupportsPictureInPicture = supportsPictureInPicture;
757 mSupportsMultiDisplay = supportsMultiDisplay;
758 } else {
759 mSupportsMultiWindow = false;
760 mSupportsFreeformWindowManagement = false;
761 mSupportsSplitScreenMultiWindow = false;
762 mSupportsPictureInPicture = false;
763 mSupportsMultiDisplay = false;
764 }
Garfield Tanb5910b42019-03-14 14:50:59 -0700765 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700766 // This happens before any activities are started, so we can change global configuration
767 // in-place.
768 updateConfigurationLocked(configuration, null, true);
769 final Configuration globalConfig = getGlobalConfiguration();
770 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
771
772 // Load resources only after the current configuration has been set.
773 final Resources res = mContext.getResources();
774 mThumbnailWidth = res.getDimensionPixelSize(
775 com.android.internal.R.dimen.thumbnail_width);
776 mThumbnailHeight = res.getDimensionPixelSize(
777 com.android.internal.R.dimen.thumbnail_height);
778
779 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
780 mFullscreenThumbnailScale = (float) res
781 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
782 (float) globalConfig.screenWidthDp;
783 } else {
784 mFullscreenThumbnailScale = res.getFraction(
785 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
786 }
787 }
788 }
789
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800790 public WindowManagerGlobalLock getGlobalLock() {
791 return mGlobalLock;
792 }
793
Yunfan Chen585f2932019-01-29 16:04:45 +0900794 /** For test purpose only. */
795 @VisibleForTesting
796 public ActivityTaskManagerInternal getAtmInternal() {
797 return mInternal;
798 }
799
Riddle Hsud93a6c42018-11-29 21:50:06 +0800800 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
801 Looper looper) {
802 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700803 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700804 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700805 final File systemDir = SystemServiceManager.ensureSystemDir();
806 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
807 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700808 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700809
810 mTempConfig.setToDefaults();
811 mTempConfig.setLocales(LocaleList.getDefault());
812 mConfigurationSeq = mTempConfig.seq = 1;
813 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800814 mRootActivityContainer = new RootActivityContainer(this);
815 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700816
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700817 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700818 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700819 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700820 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700821 setRecentTasks(new RecentTasks(this, mStackSupervisor));
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700822 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700823 mKeyguardController = mStackSupervisor.getKeyguardController();
824 }
825
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700826 public void onActivityManagerInternalAdded() {
827 synchronized (mGlobalLock) {
828 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
829 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
830 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700831 }
832
Yunfan Chen75157d72018-07-27 14:47:21 +0900833 int increaseConfigurationSeqLocked() {
834 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
835 return mConfigurationSeq;
836 }
837
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700838 protected ActivityStackSupervisor createStackSupervisor() {
839 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
840 supervisor.initialize();
841 return supervisor;
842 }
843
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700844 public void setWindowManager(WindowManagerService wm) {
845 synchronized (mGlobalLock) {
846 mWindowManager = wm;
847 mLockTaskController.setWindowManager(wm);
848 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800849 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700851 }
852
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700853 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
854 synchronized (mGlobalLock) {
855 mUsageStatsInternal = usageStatsManager;
856 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700857 }
858
Wale Ogunwalef6733932018-06-27 05:14:34 -0700859 UserManagerService getUserManager() {
860 if (mUserManager == null) {
861 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
862 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
863 }
864 return mUserManager;
865 }
866
867 AppOpsService getAppOpsService() {
868 if (mAppOpsService == null) {
869 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
870 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
871 }
872 return mAppOpsService;
873 }
874
875 boolean hasUserRestriction(String restriction, int userId) {
876 return getUserManager().hasUserRestriction(restriction, userId);
877 }
878
Michal Karpinski15486842019-04-25 17:33:42 +0100879 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
880 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
881 callingUid, callingPackage);
882 if (mode == AppOpsManager.MODE_DEFAULT) {
883 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
884 == PERMISSION_GRANTED;
885 }
886 return mode == AppOpsManager.MODE_ALLOWED;
887 }
888
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700889 @VisibleForTesting
890 protected void setRecentTasks(RecentTasks recentTasks) {
891 mRecentTasks = recentTasks;
892 mStackSupervisor.setRecentTasks(recentTasks);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700893 }
894
895 RecentTasks getRecentTasks() {
896 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700897 }
898
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700899 ClientLifecycleManager getLifecycleManager() {
900 return mLifecycleManager;
901 }
902
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700903 ActivityStartController getActivityStartController() {
904 return mActivityStartController;
905 }
906
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700907 TaskChangeNotificationController getTaskChangeNotificationController() {
908 return mTaskChangeNotificationController;
909 }
910
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700911 LockTaskController getLockTaskController() {
912 return mLockTaskController;
913 }
914
Yunfan Chen75157d72018-07-27 14:47:21 +0900915 /**
916 * Return the global configuration used by the process corresponding to the input pid. This is
917 * usually the global configuration with some overrides specific to that process.
918 */
919 Configuration getGlobalConfigurationForCallingPid() {
920 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800921 return getGlobalConfigurationForPid(pid);
922 }
923
924 /**
925 * Return the global configuration used by the process corresponding to the given pid.
926 */
927 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900928 if (pid == MY_PID || pid < 0) {
929 return getGlobalConfiguration();
930 }
931 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100932 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900933 return app != null ? app.getConfiguration() : getGlobalConfiguration();
934 }
935 }
936
937 /**
938 * Return the device configuration info used by the process corresponding to the input pid.
939 * The value is consistent with the global configuration for the process.
940 */
941 @Override
942 public ConfigurationInfo getDeviceConfigurationInfo() {
943 ConfigurationInfo config = new ConfigurationInfo();
944 synchronized (mGlobalLock) {
945 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
946 config.reqTouchScreen = globalConfig.touchscreen;
947 config.reqKeyboardType = globalConfig.keyboard;
948 config.reqNavigation = globalConfig.navigation;
949 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
950 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
951 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
952 }
953 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
954 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
955 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
956 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700957 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900958 }
959 return config;
960 }
961
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700962 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700963 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700964 }
965
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700966 public static final class Lifecycle extends SystemService {
967 private final ActivityTaskManagerService mService;
968
969 public Lifecycle(Context context) {
970 super(context);
971 mService = new ActivityTaskManagerService(context);
972 }
973
974 @Override
975 public void onStart() {
976 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700977 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700978 }
979
Garfield Tan891146c2018-10-09 12:14:00 -0700980 @Override
981 public void onUnlockUser(int userId) {
982 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800983 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700984 }
985 }
986
987 @Override
988 public void onCleanupUser(int userId) {
989 synchronized (mService.getGlobalLock()) {
990 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
991 }
992 }
993
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700994 public ActivityTaskManagerService getService() {
995 return mService;
996 }
997 }
998
999 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001000 public final int startActivity(IApplicationThread caller, String callingPackage,
1001 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1002 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1003 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1004 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1005 UserHandle.getCallingUserId());
1006 }
1007
1008 @Override
1009 public final int startActivities(IApplicationThread caller, String callingPackage,
1010 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1011 int userId) {
1012 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001013 enforceNotIsolatedCaller(reason);
1014 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001016 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1017 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1018 reason, null /* originatingPendingIntent */,
1019 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 }
1021
1022 @Override
1023 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1024 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1025 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1026 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1027 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1028 true /*validateIncomingUser*/);
1029 }
1030
Andrii Kuliana8ccae42019-07-24 18:35:22 +00001031 int startActivityAsUser(IApplicationThread caller, String callingPackage,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001032 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1033 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1034 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001037 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1039
1040 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001041 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001042 .setCaller(caller)
1043 .setCallingPackage(callingPackage)
1044 .setResolvedType(resolvedType)
1045 .setResultTo(resultTo)
1046 .setResultWho(resultWho)
1047 .setRequestCode(requestCode)
1048 .setStartFlags(startFlags)
1049 .setProfilerInfo(profilerInfo)
1050 .setActivityOptions(bOptions)
1051 .setMayWait(userId)
1052 .execute();
1053
1054 }
1055
1056 @Override
1057 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1058 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001059 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1060 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 // Refuse possible leaked file descriptors
1062 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1063 throw new IllegalArgumentException("File descriptors passed in Intent");
1064 }
1065
1066 if (!(target instanceof PendingIntentRecord)) {
1067 throw new IllegalArgumentException("Bad PendingIntent object");
1068 }
1069
1070 PendingIntentRecord pir = (PendingIntentRecord)target;
1071
1072 synchronized (mGlobalLock) {
1073 // If this is coming from the currently resumed activity, it is
1074 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001075 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001076 if (stack.mResumedActivity != null &&
1077 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001078 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 }
1080 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001081 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001082 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 }
1084
1085 @Override
1086 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1087 Bundle bOptions) {
1088 // Refuse possible leaked file descriptors
1089 if (intent != null && intent.hasFileDescriptors()) {
1090 throw new IllegalArgumentException("File descriptors passed in Intent");
1091 }
1092 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1093
1094 synchronized (mGlobalLock) {
1095 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1096 if (r == null) {
1097 SafeActivityOptions.abort(options);
1098 return false;
1099 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001100 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001101 // The caller is not running... d'oh!
1102 SafeActivityOptions.abort(options);
1103 return false;
1104 }
1105 intent = new Intent(intent);
1106 // The caller is not allowed to change the data.
1107 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1108 // And we are resetting to find the next component...
1109 intent.setComponent(null);
1110
1111 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1112
1113 ActivityInfo aInfo = null;
1114 try {
1115 List<ResolveInfo> resolves =
1116 AppGlobals.getPackageManager().queryIntentActivities(
1117 intent, r.resolvedType,
1118 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1119 UserHandle.getCallingUserId()).getList();
1120
1121 // Look for the original activity in the list...
1122 final int N = resolves != null ? resolves.size() : 0;
1123 for (int i=0; i<N; i++) {
1124 ResolveInfo rInfo = resolves.get(i);
1125 if (rInfo.activityInfo.packageName.equals(r.packageName)
1126 && rInfo.activityInfo.name.equals(r.info.name)) {
1127 // We found the current one... the next matching is
1128 // after it.
1129 i++;
1130 if (i<N) {
1131 aInfo = resolves.get(i).activityInfo;
1132 }
1133 if (debug) {
1134 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1135 + "/" + r.info.name);
1136 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1137 ? "null" : aInfo.packageName + "/" + aInfo.name));
1138 }
1139 break;
1140 }
1141 }
1142 } catch (RemoteException e) {
1143 }
1144
1145 if (aInfo == null) {
1146 // Nobody who is next!
1147 SafeActivityOptions.abort(options);
1148 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1149 return false;
1150 }
1151
1152 intent.setComponent(new ComponentName(
1153 aInfo.applicationInfo.packageName, aInfo.name));
1154 intent.setFlags(intent.getFlags()&~(
1155 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1156 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1157 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1158 FLAG_ACTIVITY_NEW_TASK));
1159
1160 // Okay now we need to start the new activity, replacing the currently running activity.
1161 // This is a little tricky because we want to start the new one as if the current one is
1162 // finished, but not finish the current one first so that there is no flicker.
1163 // And thus...
1164 final boolean wasFinishing = r.finishing;
1165 r.finishing = true;
1166
1167 // Propagate reply information over to the new activity.
1168 final ActivityRecord resultTo = r.resultTo;
1169 final String resultWho = r.resultWho;
1170 final int requestCode = r.requestCode;
1171 r.resultTo = null;
1172 if (resultTo != null) {
1173 resultTo.removeResultsLocked(r, resultWho, requestCode);
1174 }
1175
1176 final long origId = Binder.clearCallingIdentity();
1177 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001178 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001179 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001180 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001181 .setResolvedType(r.resolvedType)
1182 .setActivityInfo(aInfo)
1183 .setResultTo(resultTo != null ? resultTo.appToken : null)
1184 .setResultWho(resultWho)
1185 .setRequestCode(requestCode)
1186 .setCallingPid(-1)
1187 .setCallingUid(r.launchedFromUid)
1188 .setCallingPackage(r.launchedFromPackage)
1189 .setRealCallingPid(-1)
1190 .setRealCallingUid(r.launchedFromUid)
1191 .setActivityOptions(options)
1192 .execute();
1193 Binder.restoreCallingIdentity(origId);
1194
1195 r.finishing = wasFinishing;
1196 if (res != ActivityManager.START_SUCCESS) {
1197 return false;
1198 }
1199 return true;
1200 }
1201 }
1202
1203 @Override
1204 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1205 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1206 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1207 final WaitResult res = new WaitResult();
1208 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001209 enforceNotIsolatedCaller("startActivityAndWait");
1210 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1211 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001213 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001214 .setCaller(caller)
1215 .setCallingPackage(callingPackage)
1216 .setResolvedType(resolvedType)
1217 .setResultTo(resultTo)
1218 .setResultWho(resultWho)
1219 .setRequestCode(requestCode)
1220 .setStartFlags(startFlags)
1221 .setActivityOptions(bOptions)
1222 .setMayWait(userId)
1223 .setProfilerInfo(profilerInfo)
1224 .setWaitResult(res)
1225 .execute();
1226 }
1227 return res;
1228 }
1229
1230 @Override
1231 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1232 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1233 int startFlags, Configuration config, Bundle bOptions, int userId) {
1234 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001235 enforceNotIsolatedCaller("startActivityWithConfig");
1236 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1237 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001239 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001240 .setCaller(caller)
1241 .setCallingPackage(callingPackage)
1242 .setResolvedType(resolvedType)
1243 .setResultTo(resultTo)
1244 .setResultWho(resultWho)
1245 .setRequestCode(requestCode)
1246 .setStartFlags(startFlags)
1247 .setGlobalConfiguration(config)
1248 .setActivityOptions(bOptions)
1249 .setMayWait(userId)
1250 .execute();
1251 }
1252 }
1253
Alison Cichowlas3e340502018-08-07 17:15:01 -04001254
1255 @Override
1256 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1257 int callingUid = Binder.getCallingUid();
1258 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1259 throw new SecurityException("Only the system process can request a permission token, "
1260 + "received request from uid: " + callingUid);
1261 }
1262 IBinder permissionToken = new Binder();
1263 synchronized (mGlobalLock) {
1264 mStartActivitySources.put(permissionToken, delegatorToken);
1265 }
1266
1267 Message expireMsg = PooledLambda.obtainMessage(
1268 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1269 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1270
1271 Message forgetMsg = PooledLambda.obtainMessage(
1272 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1273 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1274
1275 return permissionToken;
1276 }
1277
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 @Override
1279 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1280 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001281 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1282 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001283 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001284 // permission grants) as any app that may launch one of your own activities. So we only
1285 // allow this in two cases:
1286 // 1) The caller is an activity that is part of the core framework, and then only when it
1287 // is running as the system.
1288 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1289 // can only be requested by a system activity, which may then delegate this call to
1290 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001291 final ActivityRecord sourceRecord;
1292 final int targetUid;
1293 final String targetPackage;
1294 final boolean isResolver;
1295 synchronized (mGlobalLock) {
1296 if (resultTo == null) {
1297 throw new SecurityException("Must be called from an activity");
1298 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001299 final IBinder sourceToken;
1300 if (permissionToken != null) {
1301 // To even attempt to use a permissionToken, an app must also have this signature
1302 // permission.
1303 mAmInternal.enforceCallingPermission(
1304 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1305 "startActivityAsCaller");
1306 // If called with a permissionToken, we want the sourceRecord from the delegator
1307 // activity that requested this token.
1308 sourceToken = mStartActivitySources.remove(permissionToken);
1309 if (sourceToken == null) {
1310 // Invalid permissionToken, check if it recently expired.
1311 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1312 throw new SecurityException("Called with expired permission token: "
1313 + permissionToken);
1314 } else {
1315 throw new SecurityException("Called with invalid permission token: "
1316 + permissionToken);
1317 }
1318 }
1319 } else {
1320 // This method was called directly by the source.
1321 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001323
Wale Ogunwaled32da472018-11-16 07:19:28 -08001324 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325 if (sourceRecord == null) {
1326 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001327 }
1328 if (sourceRecord.app == null) {
1329 throw new SecurityException("Called without a process attached to activity");
1330 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001331
1332 // Whether called directly or from a delegate, the source activity must be from the
1333 // android package.
1334 if (!sourceRecord.info.packageName.equals("android")) {
1335 throw new SecurityException("Must be called from an activity that is "
1336 + "declared in the android package");
1337 }
1338
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 // This is still okay, as long as this activity is running under the
1341 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001342 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001344 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 + " must be system uid or original calling uid "
1346 + sourceRecord.launchedFromUid);
1347 }
1348 }
1349 if (ignoreTargetSecurity) {
1350 if (intent.getComponent() == null) {
1351 throw new SecurityException(
1352 "Component must be specified with ignoreTargetSecurity");
1353 }
1354 if (intent.getSelector() != null) {
1355 throw new SecurityException(
1356 "Selector not allowed with ignoreTargetSecurity");
1357 }
1358 }
1359 targetUid = sourceRecord.launchedFromUid;
1360 targetPackage = sourceRecord.launchedFromPackage;
1361 isResolver = sourceRecord.isResolverOrChildActivity();
1362 }
1363
1364 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001365 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 }
1367
1368 // TODO: Switch to user app stacks here.
1369 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001370 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001371 .setCallingUid(targetUid)
1372 .setCallingPackage(targetPackage)
1373 .setResolvedType(resolvedType)
1374 .setResultTo(resultTo)
1375 .setResultWho(resultWho)
1376 .setRequestCode(requestCode)
1377 .setStartFlags(startFlags)
1378 .setActivityOptions(bOptions)
1379 .setMayWait(userId)
1380 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1381 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001382 // The target may well be in the background, which would normally prevent it
1383 // from starting an activity. Here we definitely want the start to succeed.
1384 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 .execute();
1386 } catch (SecurityException e) {
1387 // XXX need to figure out how to propagate to original app.
1388 // A SecurityException here is generally actually a fault of the original
1389 // calling activity (such as a fairly granting permissions), so propagate it
1390 // back to them.
1391 /*
1392 StringBuilder msg = new StringBuilder();
1393 msg.append("While launching");
1394 msg.append(intent.toString());
1395 msg.append(": ");
1396 msg.append(e.getMessage());
1397 */
1398 throw e;
1399 }
1400 }
1401
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001402 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1403 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1404 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1405 }
1406
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001407 @Override
1408 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1409 Intent intent, String resolvedType, IVoiceInteractionSession session,
1410 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1411 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001412 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 if (session == null || interactor == null) {
1414 throw new NullPointerException("null session or interactor");
1415 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001416 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001417 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001418 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 .setCallingUid(callingUid)
1420 .setCallingPackage(callingPackage)
1421 .setResolvedType(resolvedType)
1422 .setVoiceSession(session)
1423 .setVoiceInteractor(interactor)
1424 .setStartFlags(startFlags)
1425 .setProfilerInfo(profilerInfo)
1426 .setActivityOptions(bOptions)
1427 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001428 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429 .execute();
1430 }
1431
1432 @Override
1433 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1434 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001435 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1436 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001438 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439 .setCallingUid(callingUid)
1440 .setCallingPackage(callingPackage)
1441 .setResolvedType(resolvedType)
1442 .setActivityOptions(bOptions)
1443 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001444 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 .execute();
1446 }
1447
Riddle Hsu609a8e22019-06-27 16:46:29 -06001448 /**
1449 * Start the recents activity to perform the recents animation.
1450 *
1451 * @param intent The intent to start the recents activity.
1452 * @param recentsAnimationRunner Pass {@code null} to only preload the activity.
1453 */
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 @Override
Riddle Hsu609a8e22019-06-27 16:46:29 -06001455 public void startRecentsActivity(Intent intent, @Deprecated IAssistDataReceiver unused,
1456 @Nullable IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001457 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001458 final int callingPid = Binder.getCallingPid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001459 final int callingUid = Binder.getCallingUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460 final long origId = Binder.clearCallingIdentity();
1461 try {
1462 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001463 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1464 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001465 final WindowProcessController caller = getProcessController(callingPid, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001466
1467 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001468 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
Riddle Hsu609a8e22019-06-27 16:46:29 -06001469 getActivityStartController(), mWindowManager, intent, recentsComponent,
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02001470 recentsUid, caller);
Riddle Hsu609a8e22019-06-27 16:46:29 -06001471 if (recentsAnimationRunner == null) {
1472 anim.preloadRecentsActivity();
1473 } else {
1474 anim.startRecentsActivity(recentsAnimationRunner);
1475 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001476 }
1477 } finally {
1478 Binder.restoreCallingIdentity(origId);
1479 }
1480 }
1481
1482 @Override
1483 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001484 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001485 "startActivityFromRecents()");
1486
1487 final int callingPid = Binder.getCallingPid();
1488 final int callingUid = Binder.getCallingUid();
1489 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1490 final long origId = Binder.clearCallingIdentity();
1491 try {
1492 synchronized (mGlobalLock) {
1493 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1494 safeOptions);
1495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(origId);
1498 }
1499 }
1500
1501 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001502 * Public API to check if the client is allowed to start an activity on specified display.
1503 *
1504 * If the target display is private or virtual, some restrictions will apply.
1505 *
1506 * @param displayId Target display id.
1507 * @param intent Intent used to launch the activity.
1508 * @param resolvedType The MIME type of the intent.
1509 * @param userId The id of the user for whom the call is made.
1510 * @return {@code true} if a call to start an activity on the target display should succeed and
1511 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1512 */
1513 @Override
1514 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1515 String resolvedType, int userId) {
1516 final int callingUid = Binder.getCallingUid();
1517 final int callingPid = Binder.getCallingPid();
1518 final long origId = Binder.clearCallingIdentity();
1519
1520 try {
1521 // Collect information about the target of the Intent.
1522 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1523 0 /* startFlags */, null /* profilerInfo */, userId,
1524 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1525 UserHandle.USER_NULL));
1526 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1527
1528 synchronized (mGlobalLock) {
1529 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1530 aInfo);
1531 }
1532 } finally {
1533 Binder.restoreCallingIdentity(origId);
1534 }
1535 }
1536
1537 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 * This is the internal entry point for handling Activity.finish().
1539 *
1540 * @param token The Binder token referencing the Activity we want to finish.
1541 * @param resultCode Result code, if any, from this Activity.
1542 * @param resultData Result data (Intent), if any, from this Activity.
1543 * @param finishTask Whether to finish the task associated with this Activity.
1544 *
1545 * @return Returns true if the activity successfully finished, or false if it is still running.
1546 */
1547 @Override
1548 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1549 int finishTask) {
1550 // Refuse possible leaked file descriptors
1551 if (resultData != null && resultData.hasFileDescriptors()) {
1552 throw new IllegalArgumentException("File descriptors passed in Intent");
1553 }
1554
1555 synchronized (mGlobalLock) {
Andrii Kulian057a6512019-07-15 16:15:51 -07001556 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 if (r == null) {
1558 return true;
1559 }
1560 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001561 final TaskRecord tr = r.getTaskRecord();
Andrii Kulian057a6512019-07-15 16:15:51 -07001562 final ActivityRecord rootR = tr.getRootActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 if (rootR == null) {
1564 Slog.w(TAG, "Finishing task with all activities already finished");
1565 }
1566 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1567 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001568 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 return false;
1570 }
1571
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001572 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1573 // We should consolidate.
1574 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001575 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001576 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001577 if (next != null) {
1578 // ask watcher if this is allowed
1579 boolean resumeOK = true;
1580 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001581 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001582 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001583 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001584 Watchdog.getInstance().setActivityController(null);
1585 }
1586
1587 if (!resumeOK) {
1588 Slog.i(TAG, "Not finishing activity because controller resumed");
1589 return false;
1590 }
1591 }
1592 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001593
1594 // note down that the process has finished an activity and is in background activity
1595 // starts grace period
1596 if (r.app != null) {
1597 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1598 }
1599
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001600 final long origId = Binder.clearCallingIdentity();
1601 try {
1602 boolean res;
1603 final boolean finishWithRootActivity =
1604 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1605 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1606 || (finishWithRootActivity && r == rootR)) {
1607 // If requested, remove the task that is associated to this activity only if it
1608 // was the root activity in the task. The result code and data is ignored
1609 // because we don't support returning them across task boundaries. Also, to
1610 // keep backwards compatibility we remove the task from recents when finishing
1611 // task with root activity.
Andrii Kulian057a6512019-07-15 16:15:51 -07001612 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false /* killProcess */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001613 finishWithRootActivity, "finish-activity");
1614 if (!res) {
1615 Slog.i(TAG, "Removing task failed to finish activity");
1616 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001617 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001618 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001619 } else {
Louis Chang7b03ad92019-08-21 12:32:33 +08001620 r.finishIfPossible(resultCode, resultData, "app-request", true /* oomAdj */);
Andrii Kulian40eda672019-07-30 15:05:57 -07001621 res = r.finishing;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 if (!res) {
1623 Slog.i(TAG, "Failed to finish by app-request");
1624 }
1625 }
1626 return res;
1627 } finally {
1628 Binder.restoreCallingIdentity(origId);
1629 }
1630 }
1631 }
1632
1633 @Override
1634 public boolean finishActivityAffinity(IBinder token) {
1635 synchronized (mGlobalLock) {
1636 final long origId = Binder.clearCallingIdentity();
1637 try {
1638 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1639 if (r == null) {
1640 return false;
1641 }
1642
1643 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1644 // can finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001645 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001646 return false;
1647 }
Andrii Kuliande93eff2019-07-12 12:21:27 -07001648 r.finishActivityAffinity();
1649 return true;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 } finally {
1651 Binder.restoreCallingIdentity(origId);
1652 }
1653 }
1654 }
1655
1656 @Override
1657 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1658 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001659 try {
1660 WindowProcessController proc = null;
1661 synchronized (mGlobalLock) {
1662 ActivityStack stack = ActivityRecord.getStackLocked(token);
1663 if (stack == null) {
1664 return;
1665 }
1666 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1667 false /* fromTimeout */, false /* processPausingActivities */, config);
1668 if (r != null) {
1669 proc = r.app;
1670 }
1671 if (stopProfiling && proc != null) {
1672 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 }
1674 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001675 } finally {
1676 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001677 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001678 }
1679
1680 @Override
1681 public final void activityResumed(IBinder token) {
1682 final long origId = Binder.clearCallingIdentity();
1683 synchronized (mGlobalLock) {
1684 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001685 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001686 }
1687 Binder.restoreCallingIdentity(origId);
1688 }
1689
1690 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001691 public final void activityTopResumedStateLost() {
1692 final long origId = Binder.clearCallingIdentity();
1693 synchronized (mGlobalLock) {
1694 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1695 }
1696 Binder.restoreCallingIdentity(origId);
1697 }
1698
1699 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001700 public final void activityPaused(IBinder token) {
1701 final long origId = Binder.clearCallingIdentity();
1702 synchronized (mGlobalLock) {
1703 ActivityStack stack = ActivityRecord.getStackLocked(token);
1704 if (stack != null) {
1705 stack.activityPausedLocked(token, false);
1706 }
1707 }
1708 Binder.restoreCallingIdentity(origId);
1709 }
1710
1711 @Override
1712 public final void activityStopped(IBinder token, Bundle icicle,
1713 PersistableBundle persistentState, CharSequence description) {
1714 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1715
1716 // Refuse possible leaked file descriptors
1717 if (icicle != null && icicle.hasFileDescriptors()) {
1718 throw new IllegalArgumentException("File descriptors passed in Bundle");
1719 }
1720
1721 final long origId = Binder.clearCallingIdentity();
1722
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001723 String restartingName = null;
1724 int restartingUid = 0;
1725 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001727 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001729 if (r.attachedToProcess()
1730 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1731 // The activity was requested to restart from
1732 // {@link #restartActivityProcessIfVisible}.
1733 restartingName = r.app.mName;
1734 restartingUid = r.app.mUid;
1735 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001736 r.activityStoppedLocked(icicle, persistentState, description);
1737 }
1738 }
1739
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001740 if (restartingName != null) {
1741 // In order to let the foreground activity can be restarted with its saved state from
1742 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1743 // until the activity reports stopped with the state. And the activity record will be
1744 // kept because the record state is restarting, then the activity will be restarted
1745 // immediately if it is still the top one.
1746 mStackSupervisor.removeRestartTimeouts(r);
1747 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1748 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001749 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001750
1751 Binder.restoreCallingIdentity(origId);
1752 }
1753
1754 @Override
1755 public final void activityDestroyed(IBinder token) {
1756 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1757 synchronized (mGlobalLock) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001758 final long origId = Binder.clearCallingIdentity();
1759 try {
1760 final ActivityRecord activity = ActivityRecord.forTokenLocked(token);
1761 if (activity != null) {
1762 activity.destroyed("activityDestroyed");
1763 }
1764 } finally {
1765 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001766 }
1767 }
1768 }
1769
1770 @Override
1771 public final void activityRelaunched(IBinder token) {
1772 final long origId = Binder.clearCallingIdentity();
1773 synchronized (mGlobalLock) {
1774 mStackSupervisor.activityRelaunchedLocked(token);
1775 }
1776 Binder.restoreCallingIdentity(origId);
1777 }
1778
1779 public final void activitySlept(IBinder token) {
1780 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1781
1782 final long origId = Binder.clearCallingIdentity();
1783
1784 synchronized (mGlobalLock) {
1785 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1786 if (r != null) {
1787 mStackSupervisor.activitySleptLocked(r);
1788 }
1789 }
1790
1791 Binder.restoreCallingIdentity(origId);
1792 }
1793
1794 @Override
1795 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1796 synchronized (mGlobalLock) {
1797 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1798 if (r == null) {
1799 return;
1800 }
1801 final long origId = Binder.clearCallingIdentity();
1802 try {
1803 r.setRequestedOrientation(requestedOrientation);
1804 } finally {
1805 Binder.restoreCallingIdentity(origId);
1806 }
1807 }
1808 }
1809
1810 @Override
1811 public int getRequestedOrientation(IBinder token) {
1812 synchronized (mGlobalLock) {
1813 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1814 if (r == null) {
1815 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1816 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001817 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001818 }
1819 }
1820
1821 @Override
1822 public void setImmersive(IBinder token, boolean immersive) {
1823 synchronized (mGlobalLock) {
1824 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1825 if (r == null) {
1826 throw new IllegalArgumentException();
1827 }
1828 r.immersive = immersive;
1829
1830 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001831 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001833 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 }
1835 }
1836 }
1837
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001838 void applyUpdateLockStateLocked(ActivityRecord r) {
1839 // Modifications to the UpdateLock state are done on our handler, outside
1840 // the activity manager's locks. The new state is determined based on the
1841 // state *now* of the relevant activity record. The object is passed to
1842 // the handler solely for logging detail, not to be consulted/modified.
1843 final boolean nextState = r != null && r.immersive;
1844 mH.post(() -> {
1845 if (mUpdateLock.isHeld() != nextState) {
1846 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1847 "Applying new update lock state '" + nextState + "' for " + r);
1848 if (nextState) {
1849 mUpdateLock.acquire();
1850 } else {
1851 mUpdateLock.release();
1852 }
1853 }
1854 });
1855 }
1856
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001857 @Override
1858 public boolean isImmersive(IBinder token) {
1859 synchronized (mGlobalLock) {
1860 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1861 if (r == null) {
1862 throw new IllegalArgumentException();
1863 }
1864 return r.immersive;
1865 }
1866 }
1867
1868 @Override
1869 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001870 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001872 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001873 return (r != null) ? r.immersive : false;
1874 }
1875 }
1876
1877 @Override
1878 public void overridePendingTransition(IBinder token, String packageName,
1879 int enterAnim, int exitAnim) {
1880 synchronized (mGlobalLock) {
1881 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1882 if (self == null) {
1883 return;
1884 }
1885
1886 final long origId = Binder.clearCallingIdentity();
1887
1888 if (self.isState(
1889 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001890 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001891 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 }
1893
1894 Binder.restoreCallingIdentity(origId);
1895 }
1896 }
1897
1898 @Override
1899 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001900 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001902 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001903 if (r == null) {
1904 return ActivityManager.COMPAT_MODE_UNKNOWN;
1905 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001906 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001907 }
1908 }
1909
1910 @Override
1911 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001912 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001914 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001916 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001917 if (r == null) {
1918 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1919 return;
1920 }
1921 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001922 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 }
1924 }
1925
1926 @Override
1927 public int getLaunchedFromUid(IBinder activityToken) {
1928 ActivityRecord srec;
1929 synchronized (mGlobalLock) {
1930 srec = ActivityRecord.forTokenLocked(activityToken);
1931 }
1932 if (srec == null) {
1933 return -1;
1934 }
1935 return srec.launchedFromUid;
1936 }
1937
1938 @Override
1939 public String getLaunchedFromPackage(IBinder activityToken) {
1940 ActivityRecord srec;
1941 synchronized (mGlobalLock) {
1942 srec = ActivityRecord.forTokenLocked(activityToken);
1943 }
1944 if (srec == null) {
1945 return null;
1946 }
1947 return srec.launchedFromPackage;
1948 }
1949
1950 @Override
1951 public boolean convertFromTranslucent(IBinder token) {
1952 final long origId = Binder.clearCallingIdentity();
1953 try {
1954 synchronized (mGlobalLock) {
1955 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1956 if (r == null) {
1957 return false;
1958 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001959 return r.setOccludesParent(true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
1961 } finally {
1962 Binder.restoreCallingIdentity(origId);
1963 }
1964 }
1965
1966 @Override
1967 public boolean convertToTranslucent(IBinder token, Bundle options) {
1968 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1969 final long origId = Binder.clearCallingIdentity();
1970 try {
1971 synchronized (mGlobalLock) {
1972 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1973 if (r == null) {
1974 return false;
1975 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001976 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001977 int index = task.mActivities.lastIndexOf(r);
1978 if (index > 0) {
1979 ActivityRecord under = task.mActivities.get(index - 1);
1980 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1981 }
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07001982 return r.setOccludesParent(false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 }
1984 } finally {
1985 Binder.restoreCallingIdentity(origId);
1986 }
1987 }
1988
1989 @Override
1990 public void notifyActivityDrawn(IBinder token) {
1991 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1992 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001993 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001995 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 }
1997 }
1998 }
1999
2000 @Override
2001 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2002 synchronized (mGlobalLock) {
2003 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2004 if (r == null) {
2005 return;
2006 }
2007 r.reportFullyDrawnLocked(restoredFromBundle);
2008 }
2009 }
2010
2011 @Override
2012 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2013 synchronized (mGlobalLock) {
2014 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2015 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2016 return stack.mDisplayId;
2017 }
2018 return DEFAULT_DISPLAY;
2019 }
2020 }
2021
2022 @Override
2023 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 long ident = Binder.clearCallingIdentity();
2026 try {
2027 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002028 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002030 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 }
2032 return null;
2033 }
2034 } finally {
2035 Binder.restoreCallingIdentity(ident);
2036 }
2037 }
2038
2039 @Override
2040 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002041 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002042 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2043 final long callingId = Binder.clearCallingIdentity();
2044 try {
2045 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002046 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002047 if (stack == null) {
2048 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2049 return;
2050 }
2051 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002052 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002053 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 }
2055 }
2056 } finally {
2057 Binder.restoreCallingIdentity(callingId);
2058 }
2059 }
2060
2061 @Override
2062 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002063 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002068 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002069 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002070 if (task == null) {
2071 return;
2072 }
2073 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002074 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002075 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 }
2077 }
2078 } finally {
2079 Binder.restoreCallingIdentity(callingId);
2080 }
2081 }
2082
2083 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002084 public void restartActivityProcessIfVisible(IBinder activityToken) {
2085 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2086 final long callingId = Binder.clearCallingIdentity();
2087 try {
2088 synchronized (mGlobalLock) {
2089 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2090 if (r == null) {
2091 return;
2092 }
2093 r.restartProcessIfVisible();
2094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(callingId);
2097 }
2098 }
2099
2100 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002101 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002102 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002103 synchronized (mGlobalLock) {
2104 final long ident = Binder.clearCallingIdentity();
2105 try {
2106 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2107 "remove-task");
2108 } finally {
2109 Binder.restoreCallingIdentity(ident);
2110 }
2111 }
2112 }
2113
2114 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002115 public void removeAllVisibleRecentTasks() {
2116 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2117 synchronized (mGlobalLock) {
2118 final long ident = Binder.clearCallingIdentity();
2119 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002120 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002121 } finally {
2122 Binder.restoreCallingIdentity(ident);
2123 }
2124 }
2125 }
2126
2127 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2129 synchronized (mGlobalLock) {
2130 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2131 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002132 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002133 }
2134 }
2135 return false;
2136 }
2137
2138 @Override
2139 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2140 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002141
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002142 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002143 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2144 if (r != null) {
2145 return r.getActivityStack().navigateUpToLocked(
2146 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002147 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002148 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002149 }
2150 }
2151
2152 /**
2153 * Attempts to move a task backwards in z-order (the order of activities within the task is
2154 * unchanged).
2155 *
2156 * There are several possible results of this call:
2157 * - if the task is locked, then we will show the lock toast
2158 * - if there is a task behind the provided task, then that task is made visible and resumed as
2159 * this task is moved to the back
2160 * - otherwise, if there are no other tasks in the stack:
2161 * - if this task is in the pinned stack, then we remove the stack completely, which will
2162 * have the effect of moving the task to the top or bottom of the fullscreen stack
2163 * (depending on whether it is visible)
2164 * - otherwise, we simply return home and hide this task
2165 *
2166 * @param token A reference to the activity we wish to move
2167 * @param nonRoot If false then this only works if the activity is the root
2168 * of a task; if true it will work for any activity in a task.
2169 * @return Returns true if the move completed, false if not.
2170 */
2171 @Override
2172 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002173 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 synchronized (mGlobalLock) {
2175 final long origId = Binder.clearCallingIdentity();
2176 try {
2177 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002178 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 if (task != null) {
2180 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2181 }
2182 } finally {
2183 Binder.restoreCallingIdentity(origId);
2184 }
2185 }
2186 return false;
2187 }
2188
2189 @Override
2190 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 long ident = Binder.clearCallingIdentity();
2193 Rect rect = new Rect();
2194 try {
2195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2198 if (task == null) {
2199 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2200 return rect;
2201 }
2202 if (task.getStack() != null) {
2203 // Return the bounds from window manager since it will be adjusted for various
2204 // things like the presense of a docked stack for tasks that aren't resizeable.
2205 task.getWindowContainerBounds(rect);
2206 } else {
2207 // Task isn't in window manager yet since it isn't associated with a stack.
2208 // Return the persist value from activity manager
2209 if (!task.matchParentBounds()) {
2210 rect.set(task.getBounds());
2211 } else if (task.mLastNonFullscreenBounds != null) {
2212 rect.set(task.mLastNonFullscreenBounds);
2213 }
2214 }
2215 }
2216 } finally {
2217 Binder.restoreCallingIdentity(ident);
2218 }
2219 return rect;
2220 }
2221
2222 @Override
2223 public ActivityManager.TaskDescription getTaskDescription(int id) {
2224 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002225 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002227 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002228 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2229 if (tr != null) {
2230 return tr.lastTaskDescription;
2231 }
2232 }
2233 return null;
2234 }
2235
2236 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002237 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2238 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2239 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2240 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2241 return;
2242 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002244 synchronized (mGlobalLock) {
2245 final long ident = Binder.clearCallingIdentity();
2246 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002247 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002248 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002249 if (task == null) {
2250 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2251 return;
2252 }
2253
2254 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2255 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2256
2257 if (!task.isActivityTypeStandardOrUndefined()) {
2258 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2259 + " non-standard task " + taskId + " to windowing mode="
2260 + windowingMode);
2261 }
2262
2263 final ActivityStack stack = task.getStack();
2264 if (toTop) {
2265 stack.moveToFront("setTaskWindowingMode", task);
2266 }
2267 stack.setWindowingMode(windowingMode);
2268 } finally {
2269 Binder.restoreCallingIdentity(ident);
2270 }
2271 }
2272 }
2273
2274 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002275 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002276 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002277 ActivityRecord r = getCallingRecordLocked(token);
2278 return r != null ? r.info.packageName : null;
2279 }
2280 }
2281
2282 @Override
2283 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285 ActivityRecord r = getCallingRecordLocked(token);
2286 return r != null ? r.intent.getComponent() : null;
2287 }
2288 }
2289
2290 private ActivityRecord getCallingRecordLocked(IBinder token) {
2291 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2292 if (r == null) {
2293 return null;
2294 }
2295 return r.resultTo;
2296 }
2297
2298 @Override
2299 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002300 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002301
2302 synchronized (mGlobalLock) {
2303 final long origId = Binder.clearCallingIdentity();
2304 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002305 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 } finally {
2307 Binder.restoreCallingIdentity(origId);
2308 }
2309 }
2310 }
2311
Mark Renouf446251d2019-04-26 10:22:41 -04002312 @Override
2313 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2314 synchronized (mGlobalLock) {
2315 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2316 if (r == null) {
2317 return;
2318 }
2319 ActivityStack stack = r.getActivityStack();
2320 if (stack != null && stack.isSingleTaskInstance()) {
2321 // Single-task stacks are used for activities which are presented in floating
2322 // windows above full screen activities. Instead of directly finishing the
2323 // task, a task change listener is used to notify SystemUI so the action can be
2324 // handled specially.
2325 final TaskRecord task = r.getTaskRecord();
2326 mTaskChangeNotificationController
2327 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2328 } else {
2329 try {
2330 callback.requestFinish();
2331 } catch (RemoteException e) {
2332 Slog.e(TAG, "Failed to invoke request finish callback", e);
2333 }
2334 }
2335 }
2336 }
2337
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002338 /**
2339 * TODO: Add mController hook
2340 */
2341 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002342 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2343 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345
2346 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2347 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002348 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2349 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002350 }
2351 }
2352
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2354 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 boolean fromRecents) {
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002356
Ricky Waiaca8a772019-04-04 16:01:06 +01002357 final int callingPid = Binder.getCallingPid();
2358 final int callingUid = Binder.getCallingUid();
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002359 if (!isSameApp(callingUid, callingPackage)) {
2360 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2361 + Binder.getCallingPid() + " as package " + callingPackage;
2362 Slog.w(TAG, msg);
2363 throw new SecurityException(msg);
2364 }
Ricky Waiaca8a772019-04-04 16:01:06 +01002365 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 SafeActivityOptions.abort(options);
2367 return;
2368 }
2369 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002370 WindowProcessController callerApp = null;
2371 if (appThread != null) {
2372 callerApp = getProcessController(appThread);
2373 }
2374 final ActivityStarter starter = getActivityStartController().obtainStarter(
2375 null /* intent */, "moveTaskToFront");
2376 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2377 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002378 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002379 return;
2380 }
2381 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002382 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002383 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 if (task == null) {
2385 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002386 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002387 return;
2388 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002389 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002390 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002391 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 return;
2393 }
2394 ActivityOptions realOptions = options != null
2395 ? options.getOptions(mStackSupervisor)
2396 : null;
2397 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2398 false /* forceNonResizable */);
2399
2400 final ActivityRecord topActivity = task.getTopActivity();
2401 if (topActivity != null) {
2402
2403 // We are reshowing a task, use a starting window to hide the initial draw delay
2404 // so the transition can start earlier.
2405 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2406 true /* taskSwitch */, fromRecents);
2407 }
2408 } finally {
2409 Binder.restoreCallingIdentity(origId);
2410 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002411 }
2412
Ricky Waiaca8a772019-04-04 16:01:06 +01002413 /**
2414 * Return true if callingUid is system, or packageName belongs to that callingUid.
2415 */
Andrii Kuliana8ccae42019-07-24 18:35:22 +00002416 boolean isSameApp(int callingUid, @Nullable String packageName) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002417 try {
2418 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2419 if (packageName == null) {
2420 return false;
2421 }
2422 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2423 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2424 UserHandle.getUserId(callingUid));
2425 return UserHandle.isSameApp(callingUid, uid);
2426 }
2427 } catch (RemoteException e) {
2428 // Should not happen
2429 }
2430 return true;
2431 }
2432
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002433 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2434 int callingPid, int callingUid, String name) {
2435 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2436 return true;
2437 }
2438
2439 if (getRecentTasks().isCallerRecents(sourceUid)) {
2440 return true;
2441 }
2442
2443 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2444 if (perm == PackageManager.PERMISSION_GRANTED) {
2445 return true;
2446 }
2447 if (checkAllowAppSwitchUid(sourceUid)) {
2448 return true;
2449 }
2450
2451 // If the actual IPC caller is different from the logical source, then
2452 // also see if they are allowed to control app switches.
2453 if (callingUid != -1 && callingUid != sourceUid) {
2454 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2455 if (perm == PackageManager.PERMISSION_GRANTED) {
2456 return true;
2457 }
2458 if (checkAllowAppSwitchUid(callingUid)) {
2459 return true;
2460 }
2461 }
2462
2463 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2464 return false;
2465 }
2466
2467 private boolean checkAllowAppSwitchUid(int uid) {
2468 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2469 if (types != null) {
2470 for (int i = types.size() - 1; i >= 0; i--) {
2471 if (types.valueAt(i).intValue() == uid) {
2472 return true;
2473 }
2474 }
2475 }
2476 return false;
2477 }
2478
2479 @Override
2480 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2481 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2482 "setActivityController()");
2483 synchronized (mGlobalLock) {
2484 mController = controller;
2485 mControllerIsAMonkey = imAMonkey;
2486 Watchdog.getInstance().setActivityController(controller);
2487 }
2488 }
2489
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002490 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002491 synchronized (mGlobalLock) {
2492 return mController != null && mControllerIsAMonkey;
2493 }
2494 }
2495
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002496 @Override
2497 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2498 synchronized (mGlobalLock) {
2499 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2500 }
2501 }
2502
2503 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2505 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2506 }
2507
2508 @Override
2509 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2510 @WindowConfiguration.ActivityType int ignoreActivityType,
2511 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2512 final int callingUid = Binder.getCallingUid();
Nicholas Sauer0259e532019-08-30 08:24:55 -07002513 final int callingPid = Binder.getCallingPid();
2514 final boolean crossUser = isCrossUserAllowed(callingPid, callingUid);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002515 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2516
2517 synchronized (mGlobalLock) {
2518 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2519
Nicholas Sauer0259e532019-08-30 08:24:55 -07002520 final boolean allowed = isGetTasksAllowed("getTasks", callingPid, callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002521 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Nicholas Sauer0259e532019-08-30 08:24:55 -07002522 ignoreWindowingMode, callingUid, allowed, crossUser);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002523 }
2524
2525 return list;
2526 }
2527
2528 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002529 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2530 synchronized (mGlobalLock) {
2531 final long origId = Binder.clearCallingIdentity();
2532 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2533 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002534 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 }
2536 Binder.restoreCallingIdentity(origId);
2537 }
2538 }
2539
2540 @Override
2541 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002542 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002543 ActivityStack stack = ActivityRecord.getStackLocked(token);
2544 if (stack != null) {
2545 return stack.willActivityBeVisibleLocked(token);
2546 }
2547 return false;
2548 }
2549 }
2550
2551 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002553 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002554 synchronized (mGlobalLock) {
2555 final long ident = Binder.clearCallingIdentity();
2556 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002557 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 if (task == null) {
2559 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2560 return;
2561 }
2562
2563 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2564 + " to stackId=" + stackId + " toTop=" + toTop);
2565
Wale Ogunwaled32da472018-11-16 07:19:28 -08002566 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 if (stack == null) {
2568 throw new IllegalStateException(
2569 "moveTaskToStack: No stack for stackId=" + stackId);
2570 }
2571 if (!stack.isActivityTypeStandardOrUndefined()) {
2572 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2573 + taskId + " to stack " + stackId);
2574 }
2575 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002576 mWindowManager.setDockedStackCreateStateLocked(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2578 }
2579 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2580 "moveTaskToStack");
2581 } finally {
2582 Binder.restoreCallingIdentity(ident);
2583 }
2584 }
2585 }
2586
2587 @Override
Evan Roskydbe2ce52019-07-18 11:13:17 -07002588 public void animateResizePinnedStack(int stackId, Rect destBounds, int animationDuration) {
2589 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "animateResizePinnedStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002590
2591 final long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
Evan Roskydbe2ce52019-07-18 11:13:17 -07002594 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2595 if (stack == null) {
2596 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2597 return;
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002598 }
Evan Roskydbe2ce52019-07-18 11:13:17 -07002599 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2600 throw new IllegalArgumentException("Stack: " + stackId
2601 + " doesn't support animated resize.");
2602 }
2603 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2604 animationDuration, false /* fromFullscreen */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002605 }
2606 } finally {
2607 Binder.restoreCallingIdentity(ident);
2608 }
2609 }
2610
wilsonshih5c4cf522019-01-25 09:03:47 +08002611 @Override
2612 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2613 int animationDuration) {
2614 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2615
2616 final long ident = Binder.clearCallingIdentity();
2617 try {
2618 synchronized (mGlobalLock) {
2619 if (xOffset == 0 && yOffset == 0) {
2620 return;
2621 }
2622 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2623 if (stack == null) {
2624 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2625 return;
2626 }
2627 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2628 throw new IllegalArgumentException("Stack: " + stackId
2629 + " doesn't support animated resize.");
2630 }
2631 final Rect destBounds = new Rect();
2632 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002633 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002634 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2635 return;
2636 }
2637 destBounds.offset(xOffset, yOffset);
2638 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2639 animationDuration, false /* fromFullscreen */);
2640 }
2641 } finally {
2642 Binder.restoreCallingIdentity(ident);
2643 }
2644 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002645 /**
2646 * Moves the specified task to the primary-split-screen stack.
2647 *
2648 * @param taskId Id of task to move.
2649 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2650 * exist already. See
2651 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2652 * and
2653 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2654 * @param toTop If the task and stack should be moved to the top.
2655 * @param animate Whether we should play an animation for the moving the task.
2656 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2657 * stack. Pass {@code null} to use default bounds.
2658 * @param showRecents If the recents activity should be shown on the other side of the task
2659 * going into split-screen mode.
2660 */
2661 @Override
2662 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2663 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002664 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002665 "setTaskWindowingModeSplitScreenPrimary()");
2666 synchronized (mGlobalLock) {
2667 final long ident = Binder.clearCallingIdentity();
2668 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002669 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002670 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002671 if (task == null) {
2672 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2673 return false;
2674 }
2675 if (DEBUG_STACK) Slog.d(TAG_STACK,
2676 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2677 + " to createMode=" + createMode + " toTop=" + toTop);
2678 if (!task.isActivityTypeStandardOrUndefined()) {
2679 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2680 + " non-standard task " + taskId + " to split-screen windowing mode");
2681 }
2682
Wale Ogunwale83b8a6b2019-06-27 20:15:15 -07002683 mWindowManager.setDockedStackCreateStateLocked(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002684 final int windowingMode = task.getWindowingMode();
2685 final ActivityStack stack = task.getStack();
2686 if (toTop) {
2687 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2688 }
2689 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002690 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2691 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002692 return windowingMode != task.getWindowingMode();
2693 } finally {
2694 Binder.restoreCallingIdentity(ident);
2695 }
2696 }
2697 }
2698
2699 /**
2700 * Removes stacks in the input windowing modes from the system if they are of activity type
2701 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2702 */
2703 @Override
2704 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002705 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002706 "removeStacksInWindowingModes()");
2707
2708 synchronized (mGlobalLock) {
2709 final long ident = Binder.clearCallingIdentity();
2710 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002711 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002712 } finally {
2713 Binder.restoreCallingIdentity(ident);
2714 }
2715 }
2716 }
2717
2718 @Override
2719 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002720 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002721 "removeStacksWithActivityTypes()");
2722
2723 synchronized (mGlobalLock) {
2724 final long ident = Binder.clearCallingIdentity();
2725 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002726 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002732
2733 @Override
2734 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2735 int userId) {
2736 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002737 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2738 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002740 final boolean detailed = checkGetTasksPermission(
2741 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2742 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 == PackageManager.PERMISSION_GRANTED;
2744
2745 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002746 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 callingUid);
2748 }
2749 }
2750
2751 @Override
2752 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002753 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 long ident = Binder.clearCallingIdentity();
2755 try {
2756 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002757 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002758 }
2759 } finally {
2760 Binder.restoreCallingIdentity(ident);
2761 }
2762 }
2763
2764 @Override
2765 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002766 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 long ident = Binder.clearCallingIdentity();
2768 try {
2769 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002770 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002771 }
2772 } finally {
2773 Binder.restoreCallingIdentity(ident);
2774 }
2775 }
2776
2777 @Override
2778 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002779 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002780 final long callingUid = Binder.getCallingUid();
2781 final long origId = Binder.clearCallingIdentity();
2782 try {
2783 synchronized (mGlobalLock) {
2784 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea441b922019-06-27 19:21:44 -07002785 mWindowManager.cancelRecentsAnimation(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002786 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2787 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2788 }
2789 } finally {
2790 Binder.restoreCallingIdentity(origId);
2791 }
2792 }
2793
2794 @Override
2795 public void startLockTaskModeByToken(IBinder token) {
2796 synchronized (mGlobalLock) {
2797 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2798 if (r == null) {
2799 return;
2800 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002801 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 }
2803 }
2804
2805 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002806 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002807 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808 // This makes inner call to look as if it was initiated by system.
2809 long ident = Binder.clearCallingIdentity();
2810 try {
2811 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002812 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002813 MATCH_TASK_IN_STACKS_ONLY);
2814 if (task == null) {
2815 return;
2816 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817
2818 // When starting lock task mode the stack must be in front and focused
2819 task.getStack().moveToFront("startSystemLockTaskMode");
2820 startLockTaskModeLocked(task, true /* isSystemCaller */);
2821 }
2822 } finally {
2823 Binder.restoreCallingIdentity(ident);
2824 }
2825 }
2826
2827 @Override
2828 public void stopLockTaskModeByToken(IBinder token) {
2829 synchronized (mGlobalLock) {
2830 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2831 if (r == null) {
2832 return;
2833 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002834 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 }
2836 }
2837
2838 /**
2839 * This API should be called by SystemUI only when user perform certain action to dismiss
2840 * lock task mode. We should only dismiss pinned lock task mode in this case.
2841 */
2842 @Override
2843 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002844 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002845 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2846 }
2847
2848 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2849 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2850 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2851 return;
2852 }
2853
Wale Ogunwaled32da472018-11-16 07:19:28 -08002854 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002855 if (stack == null || task != stack.topTask()) {
2856 throw new IllegalArgumentException("Invalid task, not in foreground");
2857 }
2858
2859 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2860 // system or a specific app.
2861 // * System-initiated requests will only start the pinned mode (screen pinning)
2862 // * App-initiated requests
2863 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2864 // - will start the pinned mode, otherwise
2865 final int callingUid = Binder.getCallingUid();
2866 long ident = Binder.clearCallingIdentity();
2867 try {
2868 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002869 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002871 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002872 } finally {
2873 Binder.restoreCallingIdentity(ident);
2874 }
2875 }
2876
2877 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2878 final int callingUid = Binder.getCallingUid();
2879 long ident = Binder.clearCallingIdentity();
2880 try {
2881 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002882 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 }
2884 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2885 // task and jumping straight into a call in the case of emergency call back.
2886 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2887 if (tm != null) {
2888 tm.showInCallScreen(false);
2889 }
2890 } finally {
2891 Binder.restoreCallingIdentity(ident);
2892 }
2893 }
2894
2895 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002896 public void updateLockTaskPackages(int userId, String[] packages) {
2897 final int callingUid = Binder.getCallingUid();
2898 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2899 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2900 "updateLockTaskPackages()");
2901 }
2902 synchronized (this) {
2903 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2904 + Arrays.toString(packages));
2905 getLockTaskController().updateLockTaskPackages(userId, packages);
2906 }
2907 }
2908
2909 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002910 public boolean isInLockTaskMode() {
2911 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2912 }
2913
2914 @Override
2915 public int getLockTaskModeState() {
2916 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002917 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 }
2919 }
2920
2921 @Override
2922 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2923 synchronized (mGlobalLock) {
2924 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2925 if (r != null) {
2926 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002927 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002928 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002929 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 }
2931 }
2932 }
2933
2934 @Override
2935 public Bundle getActivityOptions(IBinder token) {
2936 final long origId = Binder.clearCallingIdentity();
2937 try {
2938 synchronized (mGlobalLock) {
2939 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2940 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002941 final ActivityOptions activityOptions = r.takeOptionsLocked(
2942 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 return activityOptions == null ? null : activityOptions.toBundle();
2944 }
2945 return null;
2946 }
2947 } finally {
2948 Binder.restoreCallingIdentity(origId);
2949 }
2950 }
2951
2952 @Override
2953 public List<IBinder> getAppTasks(String callingPackage) {
2954 int callingUid = Binder.getCallingUid();
2955 long ident = Binder.clearCallingIdentity();
2956 try {
2957 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002958 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002959 }
2960 } finally {
2961 Binder.restoreCallingIdentity(ident);
2962 }
2963 }
2964
2965 @Override
2966 public void finishVoiceTask(IVoiceInteractionSession session) {
2967 synchronized (mGlobalLock) {
2968 final long origId = Binder.clearCallingIdentity();
2969 try {
2970 // TODO: VI Consider treating local voice interactions and voice tasks
2971 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002972 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 } finally {
2974 Binder.restoreCallingIdentity(origId);
2975 }
2976 }
2977
2978 }
2979
2980 @Override
2981 public boolean isTopOfTask(IBinder token) {
2982 synchronized (mGlobalLock) {
2983 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002984 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 }
2986 }
2987
2988 @Override
2989 public void notifyLaunchTaskBehindComplete(IBinder token) {
2990 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2991 }
2992
2993 @Override
2994 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002995 mH.post(() -> {
2996 synchronized (mGlobalLock) {
2997 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002998 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002999 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003000 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003001 } catch (RemoteException e) {
3002 }
3003 }
3004 }
3005
3006 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003007 }
3008
3009 /** Called from an app when assist data is ready. */
3010 @Override
3011 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3012 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003013 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 synchronized (pae) {
3015 pae.result = extras;
3016 pae.structure = structure;
3017 pae.content = content;
3018 if (referrer != null) {
3019 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3020 }
3021 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003022 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003023 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3024 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 structure.setHomeActivity(pae.isHome);
3026 }
3027 pae.haveResult = true;
3028 pae.notifyAll();
3029 if (pae.intent == null && pae.receiver == null) {
3030 // Caller is just waiting for the result.
3031 return;
3032 }
3033 }
3034 // We are now ready to launch the assist activity.
3035 IAssistDataReceiver sendReceiver = null;
3036 Bundle sendBundle = null;
3037 synchronized (mGlobalLock) {
3038 buildAssistBundleLocked(pae, extras);
3039 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003040 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003041 if (!exists) {
3042 // Timed out.
3043 return;
3044 }
3045
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003046 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 // Caller wants result sent back to them.
3048 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003049 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3050 pae.activity.getTaskRecord().taskId);
3051 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3052 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003053 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3054 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3055 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3056 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3057 }
3058 }
3059 if (sendReceiver != null) {
3060 try {
3061 sendReceiver.onHandleAssistData(sendBundle);
3062 } catch (RemoteException e) {
3063 }
3064 return;
3065 }
3066
3067 final long ident = Binder.clearCallingIdentity();
3068 try {
3069 if (TextUtils.equals(pae.intent.getAction(),
3070 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003071 // Start voice interaction through VoiceInteractionManagerService.
3072 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3073 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003074 } else {
3075 pae.intent.replaceExtras(pae.extras);
3076 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3077 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3078 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003079 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080
3081 try {
3082 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3083 } catch (ActivityNotFoundException e) {
3084 Slog.w(TAG, "No activity to handle assist action.", e);
3085 }
3086 }
3087 } finally {
3088 Binder.restoreCallingIdentity(ident);
3089 }
3090 }
3091
3092 @Override
3093 public int addAppTask(IBinder activityToken, Intent intent,
3094 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3095 final int callingUid = Binder.getCallingUid();
3096 final long callingIdent = Binder.clearCallingIdentity();
3097
3098 try {
3099 synchronized (mGlobalLock) {
3100 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3101 if (r == null) {
3102 throw new IllegalArgumentException("Activity does not exist; token="
3103 + activityToken);
3104 }
3105 ComponentName comp = intent.getComponent();
3106 if (comp == null) {
3107 throw new IllegalArgumentException("Intent " + intent
3108 + " must specify explicit component");
3109 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 if (thumbnail.getWidth() != mThumbnailWidth
3111 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 throw new IllegalArgumentException("Bad thumbnail size: got "
3113 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003114 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 }
3116 if (intent.getSelector() != null) {
3117 intent.setSelector(null);
3118 }
3119 if (intent.getSourceBounds() != null) {
3120 intent.setSourceBounds(null);
3121 }
3122 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3123 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3124 // The caller has added this as an auto-remove task... that makes no
3125 // sense, so turn off auto-remove.
3126 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3127 }
3128 }
3129 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3130 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3131 if (ainfo.applicationInfo.uid != callingUid) {
3132 throw new SecurityException(
3133 "Can't add task for another application: target uid="
3134 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3135 }
3136
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003137 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003138 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003139 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003141 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142 // The app has too many tasks already and we can't add any more
3143 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3144 return INVALID_TASK_ID;
3145 }
3146 task.lastTaskDescription.copyFrom(description);
3147
3148 // TODO: Send the thumbnail to WM to store it.
3149
3150 return task.taskId;
3151 }
3152 } finally {
3153 Binder.restoreCallingIdentity(callingIdent);
3154 }
3155 }
3156
3157 @Override
3158 public Point getAppTaskThumbnailSize() {
3159 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003160 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 }
3162 }
3163
3164 @Override
3165 public void setTaskResizeable(int taskId, int resizeableMode) {
3166 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003167 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3169 if (task == null) {
3170 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3171 return;
3172 }
3173 task.setResizeMode(resizeableMode);
3174 }
3175 }
3176
3177 @Override
3178 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003179 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 long ident = Binder.clearCallingIdentity();
3181 try {
3182 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003183 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003184 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 if (task == null) {
3186 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3187 return;
3188 }
3189 // Place the task in the right stack if it isn't there already based on
3190 // the requested bounds.
3191 // The stack transition logic is:
3192 // - a null bounds on a freeform task moves that task to fullscreen
3193 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3194 // that task to freeform
3195 // - otherwise the task is not moved
3196 ActivityStack stack = task.getStack();
3197 if (!task.getWindowConfiguration().canResizeTask()) {
3198 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3199 }
3200 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3201 stack = stack.getDisplay().getOrCreateStack(
3202 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3203 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3204 stack = stack.getDisplay().getOrCreateStack(
3205 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3206 }
3207
3208 // Reparent the task to the right stack if necessary
3209 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3210 if (stack != task.getStack()) {
3211 // Defer resume until the task is resized below
3212 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3213 DEFER_RESUME, "resizeTask");
3214 preserveWindow = false;
3215 }
3216
3217 // After reparenting (which only resizes the task to the stack bounds), resize the
3218 // task to the actual bounds provided
3219 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3220 }
3221 } finally {
3222 Binder.restoreCallingIdentity(ident);
3223 }
3224 }
3225
3226 @Override
3227 public boolean releaseActivityInstance(IBinder token) {
3228 synchronized (mGlobalLock) {
3229 final long origId = Binder.clearCallingIdentity();
3230 try {
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003231 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3232 if (r == null || !r.isDestroyable()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 return false;
3234 }
Andrii Kulianf49a58c2019-08-14 17:34:27 -07003235 r.destroyImmediately(true /* removeFromApp */, "app-req");
3236 return r.isState(DESTROYING, DESTROYED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003237 } finally {
3238 Binder.restoreCallingIdentity(origId);
3239 }
3240 }
3241 }
3242
3243 @Override
3244 public void releaseSomeActivities(IApplicationThread appInt) {
3245 synchronized (mGlobalLock) {
3246 final long origId = Binder.clearCallingIdentity();
3247 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003248 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003249 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003250 } finally {
3251 Binder.restoreCallingIdentity(origId);
3252 }
3253 }
3254 }
3255
3256 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003257 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003258 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003259 != PackageManager.PERMISSION_GRANTED) {
3260 throw new SecurityException("Requires permission "
3261 + android.Manifest.permission.DEVICE_POWER);
3262 }
3263
3264 synchronized (mGlobalLock) {
3265 long ident = Binder.clearCallingIdentity();
3266 if (mKeyguardShown != keyguardShowing) {
3267 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003268 final Message msg = PooledLambda.obtainMessage(
3269 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3270 keyguardShowing);
3271 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 }
3273 try {
wilsonshih177261f2019-02-22 12:02:18 +08003274 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003275 } finally {
3276 Binder.restoreCallingIdentity(ident);
3277 }
3278 }
3279
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 mH.post(() -> {
3281 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3282 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3283 }
3284 });
3285 }
3286
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003287 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003288 mH.post(() -> {
3289 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3290 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3291 }
3292 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003293 }
3294
3295 @Override
3296 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003297 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3298 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299
3300 final File passedIconFile = new File(filePath);
3301 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3302 passedIconFile.getName());
3303 if (!legitIconFile.getPath().equals(filePath)
3304 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3305 throw new IllegalArgumentException("Bad file path: " + filePath
3306 + " passed for userId " + userId);
3307 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003308 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 }
3310
3311 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003312 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003313 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3314 final ActivityOptions activityOptions = safeOptions != null
3315 ? safeOptions.getOptions(mStackSupervisor)
3316 : null;
3317 if (activityOptions == null
3318 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3319 || activityOptions.getCustomInPlaceResId() == 0) {
3320 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3321 "with valid animation");
3322 }
lumark588a3e82018-07-20 18:53:54 +08003323 // Get top display of front most application.
3324 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3325 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003326 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3327 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3328 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003329 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003330 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003331 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003332 }
3333
3334 @Override
3335 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003336 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 synchronized (mGlobalLock) {
3338 final long ident = Binder.clearCallingIdentity();
3339 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003340 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003341 if (stack == null) {
3342 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3343 return;
3344 }
3345 if (!stack.isActivityTypeStandardOrUndefined()) {
3346 throw new IllegalArgumentException(
3347 "Removing non-standard stack is not allowed.");
3348 }
3349 mStackSupervisor.removeStack(stack);
3350 } finally {
3351 Binder.restoreCallingIdentity(ident);
3352 }
3353 }
3354 }
3355
3356 @Override
3357 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003358 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003359
3360 synchronized (mGlobalLock) {
3361 final long ident = Binder.clearCallingIdentity();
3362 try {
3363 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3364 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003365 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 } finally {
3367 Binder.restoreCallingIdentity(ident);
3368 }
3369 }
3370 }
3371
3372 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003373 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 synchronized (mGlobalLock) {
3375 long ident = Binder.clearCallingIdentity();
3376 try {
3377 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3378 if (r == null) {
3379 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003380 "toggleFreeformWindowingMode: No activity record matching token="
3381 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 }
3383
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003384 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003385 if (stack == null) {
3386 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3387 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 }
3389
Yunfan Chend967af82019-01-17 18:30:18 +09003390 if (!stack.inFreeformWindowingMode()
3391 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3392 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3393 + "toggle between fullscreen and freeform.");
3394 }
3395
3396 if (stack.inFreeformWindowingMode()) {
3397 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003398 } else if (stack.getParent().inFreeformWindowingMode()) {
3399 // If the window is on a freeform display, set it to undefined. It will be
3400 // resolved to freeform and it can adjust windowing mode when the display mode
3401 // changes in runtime.
3402 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003403 } else {
3404 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3405 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003406 } finally {
3407 Binder.restoreCallingIdentity(ident);
3408 }
3409 }
3410 }
3411
3412 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3413 @Override
3414 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003417 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 }
3419
3420 /** Unregister a task stack listener so that it stops receiving callbacks. */
3421 @Override
3422 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003423 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003425 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003426 }
3427
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 @Override
3429 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3430 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3431 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3432 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3433 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3434 }
3435
3436 @Override
3437 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3438 IBinder activityToken, int flags) {
3439 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3440 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3441 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3442 }
3443
3444 @Override
3445 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3446 Bundle args) {
3447 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3448 true /* focused */, true /* newSessionId */, userHandle, args,
3449 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3450 }
3451
3452 @Override
3453 public Bundle getAssistContextExtras(int requestType) {
3454 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3455 null, null, true /* focused */, true /* newSessionId */,
3456 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3457 if (pae == null) {
3458 return null;
3459 }
3460 synchronized (pae) {
3461 while (!pae.haveResult) {
3462 try {
3463 pae.wait();
3464 } catch (InterruptedException e) {
3465 }
3466 }
3467 }
3468 synchronized (mGlobalLock) {
3469 buildAssistBundleLocked(pae, pae.result);
3470 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003471 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003472 }
3473 return pae.extras;
3474 }
3475
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003476 /**
3477 * Binder IPC calls go through the public entry point.
3478 * This can be called with or without the global lock held.
3479 */
3480 private static int checkCallingPermission(String permission) {
3481 return checkPermission(
3482 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3483 }
3484
3485 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003486 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003487 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3488 mAmInternal.enforceCallingPermission(permission, func);
3489 }
3490 }
3491
3492 @VisibleForTesting
3493 int checkGetTasksPermission(String permission, int pid, int uid) {
3494 return checkPermission(permission, pid, uid);
3495 }
3496
3497 static int checkPermission(String permission, int pid, int uid) {
3498 if (permission == null) {
3499 return PackageManager.PERMISSION_DENIED;
3500 }
3501 return checkComponentPermission(permission, pid, uid, -1, true);
3502 }
3503
Wale Ogunwale214f3482018-10-04 11:00:47 -07003504 public static int checkComponentPermission(String permission, int pid, int uid,
3505 int owningUid, boolean exported) {
3506 return ActivityManagerService.checkComponentPermission(
3507 permission, pid, uid, owningUid, exported);
3508 }
3509
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003510 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3511 if (getRecentTasks().isCallerRecents(callingUid)) {
3512 // Always allow the recents component to get tasks
3513 return true;
3514 }
3515
3516 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3517 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3518 if (!allowed) {
3519 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3520 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3521 // Temporary compatibility: some existing apps on the system image may
3522 // still be requesting the old permission and not switched to the new
3523 // one; if so, we'll still allow them full access. This means we need
3524 // to see if they are holding the old permission and are a system app.
3525 try {
3526 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3527 allowed = true;
3528 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3529 + " is using old GET_TASKS but privileged; allowing");
3530 }
3531 } catch (RemoteException e) {
3532 }
3533 }
3534 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3535 + " does not hold REAL_GET_TASKS; limiting output");
3536 }
3537 return allowed;
3538 }
3539
Nicholas Sauer0259e532019-08-30 08:24:55 -07003540 boolean isCrossUserAllowed(int pid, int uid) {
3541 return checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
3542 || checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid) == PERMISSION_GRANTED;
3543 }
3544
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003545 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3546 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3547 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3548 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003549 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003550 "enqueueAssistContext()");
3551
3552 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003553 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 if (activity == null) {
3555 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3556 return null;
3557 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003558 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003559 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3560 return null;
3561 }
3562 if (focused) {
3563 if (activityToken != null) {
3564 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3565 if (activity != caller) {
3566 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3567 + " is not current top " + activity);
3568 return null;
3569 }
3570 }
3571 } else {
3572 activity = ActivityRecord.forTokenLocked(activityToken);
3573 if (activity == null) {
3574 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3575 + " couldn't be found");
3576 return null;
3577 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003578 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003579 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3580 return null;
3581 }
3582 }
3583
3584 PendingAssistExtras pae;
3585 Bundle extras = new Bundle();
3586 if (args != null) {
3587 extras.putAll(args);
3588 }
3589 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003590 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591
3592 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3593 userHandle);
3594 pae.isHome = activity.isActivityTypeHome();
3595
3596 // Increment the sessionId if necessary
3597 if (newSessionId) {
3598 mViSessionId++;
3599 }
3600 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003601 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3602 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003604 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003605 } catch (RemoteException e) {
3606 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3607 return null;
3608 }
3609 return pae;
3610 }
3611 }
3612
3613 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3614 if (result != null) {
3615 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3616 }
3617 if (pae.hint != null) {
3618 pae.extras.putBoolean(pae.hint, true);
3619 }
3620 }
3621
3622 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3623 IAssistDataReceiver receiver;
3624 synchronized (mGlobalLock) {
3625 mPendingAssistExtras.remove(pae);
3626 receiver = pae.receiver;
3627 }
3628 if (receiver != null) {
3629 // Caller wants result sent back to them.
3630 Bundle sendBundle = new Bundle();
3631 // At least return the receiver extras
3632 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3633 try {
3634 pae.receiver.onHandleAssistData(sendBundle);
3635 } catch (RemoteException e) {
3636 }
3637 }
3638 }
3639
3640 public class PendingAssistExtras extends Binder implements Runnable {
3641 public final ActivityRecord activity;
3642 public boolean isHome;
3643 public final Bundle extras;
3644 public final Intent intent;
3645 public final String hint;
3646 public final IAssistDataReceiver receiver;
3647 public final int userHandle;
3648 public boolean haveResult = false;
3649 public Bundle result = null;
3650 public AssistStructure structure = null;
3651 public AssistContent content = null;
3652 public Bundle receiverExtras;
3653
3654 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3655 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3656 int _userHandle) {
3657 activity = _activity;
3658 extras = _extras;
3659 intent = _intent;
3660 hint = _hint;
3661 receiver = _receiver;
3662 receiverExtras = _receiverExtras;
3663 userHandle = _userHandle;
3664 }
3665
3666 @Override
3667 public void run() {
3668 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3669 synchronized (this) {
3670 haveResult = true;
3671 notifyAll();
3672 }
3673 pendingAssistExtrasTimedOut(this);
3674 }
3675 }
3676
3677 @Override
3678 public boolean isAssistDataAllowedOnCurrentActivity() {
3679 int userId;
3680 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003681 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003682 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3683 return false;
3684 }
3685
3686 final ActivityRecord activity = focusedStack.getTopActivity();
3687 if (activity == null) {
3688 return false;
3689 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003690 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003691 }
3692 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3693 }
3694
3695 @Override
3696 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3697 long ident = Binder.clearCallingIdentity();
3698 try {
3699 synchronized (mGlobalLock) {
3700 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003701 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003702 if (top != caller) {
3703 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3704 + " is not current top " + top);
3705 return false;
3706 }
3707 if (!top.nowVisible) {
3708 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3709 + " is not visible");
3710 return false;
3711 }
3712 }
3713 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3714 token);
3715 } finally {
3716 Binder.restoreCallingIdentity(ident);
3717 }
3718 }
3719
3720 @Override
3721 public boolean isRootVoiceInteraction(IBinder token) {
3722 synchronized (mGlobalLock) {
3723 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3724 if (r == null) {
3725 return false;
3726 }
3727 return r.rootVoiceInteraction;
3728 }
3729 }
3730
Wale Ogunwalef6733932018-06-27 05:14:34 -07003731 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3732 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3733 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3734 if (activityToCallback == null) return;
3735 activityToCallback.setVoiceSessionLocked(voiceSession);
3736
3737 // Inform the activity
3738 try {
3739 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3740 voiceInteractor);
3741 long token = Binder.clearCallingIdentity();
3742 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003743 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003744 } finally {
3745 Binder.restoreCallingIdentity(token);
3746 }
3747 // TODO: VI Should we cache the activity so that it's easier to find later
3748 // rather than scan through all the stacks and activities?
3749 } catch (RemoteException re) {
3750 activityToCallback.clearVoiceSessionLocked();
3751 // TODO: VI Should this terminate the voice session?
3752 }
3753 }
3754
3755 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3756 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3757 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3758 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3759 boolean wasRunningVoice = mRunningVoice != null;
3760 mRunningVoice = session;
3761 if (!wasRunningVoice) {
3762 mVoiceWakeLock.acquire();
3763 updateSleepIfNeededLocked();
3764 }
3765 }
3766 }
3767
3768 void finishRunningVoiceLocked() {
3769 if (mRunningVoice != null) {
3770 mRunningVoice = null;
3771 mVoiceWakeLock.release();
3772 updateSleepIfNeededLocked();
3773 }
3774 }
3775
3776 @Override
3777 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3778 synchronized (mGlobalLock) {
3779 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3780 if (keepAwake) {
3781 mVoiceWakeLock.acquire();
3782 } else {
3783 mVoiceWakeLock.release();
3784 }
3785 }
3786 }
3787 }
3788
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003789 @Override
3790 public ComponentName getActivityClassForToken(IBinder token) {
3791 synchronized (mGlobalLock) {
3792 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3793 if (r == null) {
3794 return null;
3795 }
3796 return r.intent.getComponent();
3797 }
3798 }
3799
3800 @Override
3801 public String getPackageForToken(IBinder token) {
3802 synchronized (mGlobalLock) {
3803 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3804 if (r == null) {
3805 return null;
3806 }
3807 return r.packageName;
3808 }
3809 }
3810
3811 @Override
3812 public void showLockTaskEscapeMessage(IBinder token) {
3813 synchronized (mGlobalLock) {
3814 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3815 if (r == null) {
3816 return;
3817 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003818 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003819 }
3820 }
3821
3822 @Override
3823 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003824 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003825 final long token = Binder.clearCallingIdentity();
3826 try {
3827 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003828 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 }
3830 } finally {
3831 Binder.restoreCallingIdentity(token);
3832 }
3833 }
3834
3835 /**
3836 * Try to place task to provided position. The final position might be different depending on
3837 * current user and stacks state. The task will be moved to target stack if it's currently in
3838 * different stack.
3839 */
3840 @Override
3841 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003842 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 synchronized (mGlobalLock) {
3844 long ident = Binder.clearCallingIdentity();
3845 try {
3846 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3847 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003848 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003849 if (task == null) {
3850 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3851 + taskId);
3852 }
3853
Wale Ogunwaled32da472018-11-16 07:19:28 -08003854 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003855
3856 if (stack == null) {
3857 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3858 + stackId);
3859 }
3860 if (!stack.isActivityTypeStandardOrUndefined()) {
3861 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3862 + " the position of task " + taskId + " in/to non-standard stack");
3863 }
3864
3865 // TODO: Have the callers of this API call a separate reparent method if that is
3866 // what they intended to do vs. having this method also do reparenting.
3867 if (task.getStack() == stack) {
3868 // Change position in current stack.
3869 stack.positionChildAt(task, position);
3870 } else {
3871 // Reparent to new stack.
3872 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3873 !DEFER_RESUME, "positionTaskInStack");
3874 }
3875 } finally {
3876 Binder.restoreCallingIdentity(ident);
3877 }
3878 }
3879 }
3880
3881 @Override
3882 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3883 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3884 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003885 + Arrays.toString(horizontalSizeConfiguration) + " "
3886 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003887 synchronized (mGlobalLock) {
3888 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3889 if (record == null) {
3890 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3891 + "found for: " + token);
3892 }
3893 record.setSizeConfigurations(horizontalSizeConfiguration,
3894 verticalSizeConfigurations, smallestSizeConfigurations);
3895 }
3896 }
3897
3898 /**
3899 * Dismisses split-screen multi-window mode.
3900 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3901 */
3902 @Override
3903 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003904 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003905 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3906 final long ident = Binder.clearCallingIdentity();
3907 try {
3908 synchronized (mGlobalLock) {
3909 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003910 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 if (stack == null) {
3912 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3913 return;
3914 }
3915
3916 if (toTop) {
3917 // Caller wants the current split-screen primary stack to be the top stack after
3918 // it goes fullscreen, so move it to the front.
3919 stack.moveToFront("dismissSplitScreenMode");
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003920 } else {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003921 // In this case the current split-screen primary stack shouldn't be the top
JinsungKim6e7fd3e2019-06-17 18:31:28 +09003922 // stack after it goes fullscreen, so we move the focus to the top-most
3923 // split-screen secondary stack next to it.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003924 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3925 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3926 if (otherStack != null) {
3927 otherStack.moveToFront("dismissSplitScreenMode_other");
3928 }
3929 }
3930
Evan Rosky10475742018-09-05 19:02:48 -07003931 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003932 }
3933 } finally {
3934 Binder.restoreCallingIdentity(ident);
3935 }
3936 }
3937
3938 /**
3939 * Dismisses Pip
3940 * @param animate True if the dismissal should be animated.
3941 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3942 * default animation duration should be used.
3943 */
3944 @Override
3945 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003946 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947 final long ident = Binder.clearCallingIdentity();
3948 try {
3949 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003950 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003951 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003952 if (stack == null) {
3953 Slog.w(TAG, "dismissPip: pinned stack not found.");
3954 return;
3955 }
3956 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3957 throw new IllegalArgumentException("Stack: " + stack
3958 + " doesn't support animated resize.");
3959 }
3960 if (animate) {
3961 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3962 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3963 } else {
3964 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3965 }
3966 }
3967 } finally {
3968 Binder.restoreCallingIdentity(ident);
3969 }
3970 }
3971
3972 @Override
3973 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003974 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 synchronized (mGlobalLock) {
3976 mSuppressResizeConfigChanges = suppress;
3977 }
3978 }
3979
3980 /**
3981 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3982 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3983 * activity and clearing the task at the same time.
3984 */
3985 @Override
3986 // TODO: API should just be about changing windowing modes...
3987 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003989 "moveTasksToFullscreenStack()");
3990 synchronized (mGlobalLock) {
3991 final long origId = Binder.clearCallingIdentity();
3992 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003993 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003994 if (stack != null){
3995 if (!stack.isActivityTypeStandardOrUndefined()) {
3996 throw new IllegalArgumentException(
3997 "You can't move tasks from non-standard stacks.");
3998 }
3999 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4000 }
4001 } finally {
4002 Binder.restoreCallingIdentity(origId);
4003 }
4004 }
4005 }
4006
4007 /**
4008 * Moves the top activity in the input stackId to the pinned stack.
4009 *
4010 * @param stackId Id of stack to move the top activity to pinned stack.
4011 * @param bounds Bounds to use for pinned stack.
4012 *
4013 * @return True if the top activity of the input stack was successfully moved to the pinned
4014 * stack.
4015 */
4016 @Override
4017 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004018 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004019 "moveTopActivityToPinnedStack()");
4020 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004021 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4023 + "Device doesn't support picture-in-picture mode");
4024 }
4025
4026 long ident = Binder.clearCallingIdentity();
4027 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004028 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 } finally {
4030 Binder.restoreCallingIdentity(ident);
4031 }
4032 }
4033 }
4034
4035 @Override
4036 public boolean isInMultiWindowMode(IBinder token) {
4037 final long origId = Binder.clearCallingIdentity();
4038 try {
4039 synchronized (mGlobalLock) {
4040 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4041 if (r == null) {
4042 return false;
4043 }
4044 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4045 return r.inMultiWindowMode();
4046 }
4047 } finally {
4048 Binder.restoreCallingIdentity(origId);
4049 }
4050 }
4051
4052 @Override
4053 public boolean isInPictureInPictureMode(IBinder token) {
4054 final long origId = Binder.clearCallingIdentity();
4055 try {
4056 synchronized (mGlobalLock) {
4057 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4058 }
4059 } finally {
4060 Binder.restoreCallingIdentity(origId);
4061 }
4062 }
4063
4064 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004065 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4066 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004067 return false;
4068 }
4069
4070 // If we are animating to fullscreen then we have already dispatched the PIP mode
4071 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004072 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4073 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 }
4075
4076 @Override
4077 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4078 final long origId = Binder.clearCallingIdentity();
4079 try {
4080 synchronized (mGlobalLock) {
4081 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4082 "enterPictureInPictureMode", token, params);
4083
4084 // If the activity is already in picture in picture mode, then just return early
4085 if (isInPictureInPictureMode(r)) {
4086 return true;
4087 }
4088
4089 // Activity supports picture-in-picture, now check that we can enter PiP at this
4090 // point, if it is
4091 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4092 false /* beforeStopping */)) {
4093 return false;
4094 }
4095
4096 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004097 synchronized (mGlobalLock) {
4098 // Only update the saved args from the args that are set
4099 r.pictureInPictureArgs.copyOnlySet(params);
4100 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4101 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4102 // Adjust the source bounds by the insets for the transition down
4103 final Rect sourceBounds = new Rect(
4104 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004105 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004106 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004107 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004108 stack.setPictureInPictureAspectRatio(aspectRatio);
4109 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004110 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4111 r.info.applicationInfo.uid, r.shortComponentName,
4112 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004113 logPictureInPictureArgs(params);
4114 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 };
4116
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004117 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 // If the keyguard is showing or occluded, then try and dismiss it before
4119 // entering picture-in-picture (this will prompt the user to authenticate if the
4120 // device is currently locked).
4121 dismissKeyguard(token, new KeyguardDismissCallback() {
4122 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004123 public void onDismissSucceeded() {
4124 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 }
4126 }, null /* message */);
4127 } else {
4128 // Enter picture in picture immediately otherwise
4129 enterPipRunnable.run();
4130 }
4131 return true;
4132 }
4133 } finally {
4134 Binder.restoreCallingIdentity(origId);
4135 }
4136 }
4137
4138 @Override
4139 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4140 final long origId = Binder.clearCallingIdentity();
4141 try {
4142 synchronized (mGlobalLock) {
4143 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4144 "setPictureInPictureParams", token, params);
4145
4146 // Only update the saved args from the args that are set
4147 r.pictureInPictureArgs.copyOnlySet(params);
4148 if (r.inPinnedWindowingMode()) {
4149 // If the activity is already in picture-in-picture, update the pinned stack now
4150 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4151 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004152 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004153 if (!stack.isAnimatingBoundsToFullscreen()) {
4154 stack.setPictureInPictureAspectRatio(
4155 r.pictureInPictureArgs.getAspectRatio());
4156 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4157 }
4158 }
4159 logPictureInPictureArgs(params);
4160 }
4161 } finally {
4162 Binder.restoreCallingIdentity(origId);
4163 }
4164 }
4165
4166 @Override
4167 public int getMaxNumPictureInPictureActions(IBinder token) {
4168 // Currently, this is a static constant, but later, we may change this to be dependent on
4169 // the context of the activity
4170 return 3;
4171 }
4172
4173 private void logPictureInPictureArgs(PictureInPictureParams params) {
4174 if (params.hasSetActions()) {
4175 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4176 params.getActions().size());
4177 }
4178 if (params.hasSetAspectRatio()) {
4179 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4180 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4181 MetricsLogger.action(lm);
4182 }
4183 }
4184
4185 /**
4186 * Checks the state of the system and the activity associated with the given {@param token} to
4187 * verify that picture-in-picture is supported for that activity.
4188 *
4189 * @return the activity record for the given {@param token} if all the checks pass.
4190 */
4191 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4192 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004193 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004194 throw new IllegalStateException(caller
4195 + ": Device doesn't support picture-in-picture mode.");
4196 }
4197
4198 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4199 if (r == null) {
4200 throw new IllegalStateException(caller
4201 + ": Can't find activity for token=" + token);
4202 }
4203
4204 if (!r.supportsPictureInPicture()) {
4205 throw new IllegalStateException(caller
4206 + ": Current activity does not support picture-in-picture.");
4207 }
4208
4209 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004210 && !mWindowManager.isValidPictureInPictureAspectRatio(
4211 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 final float minAspectRatio = mContext.getResources().getFloat(
4213 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4214 final float maxAspectRatio = mContext.getResources().getFloat(
4215 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4216 throw new IllegalArgumentException(String.format(caller
4217 + ": Aspect ratio is too extreme (must be between %f and %f).",
4218 minAspectRatio, maxAspectRatio));
4219 }
4220
4221 // Truncate the number of actions if necessary
4222 params.truncateActions(getMaxNumPictureInPictureActions(token));
4223
4224 return r;
4225 }
4226
4227 @Override
4228 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004229 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 synchronized (mGlobalLock) {
4231 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4232 if (r == null) {
4233 throw new IllegalArgumentException("Activity does not exist; token="
4234 + activityToken);
4235 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004236 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 }
4238 }
4239
4240 @Override
4241 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4242 Rect tempDockedTaskInsetBounds,
4243 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 long ident = Binder.clearCallingIdentity();
4246 try {
4247 synchronized (mGlobalLock) {
4248 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4249 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4250 PRESERVE_WINDOWS);
4251 }
4252 } finally {
4253 Binder.restoreCallingIdentity(ident);
4254 }
4255 }
4256
4257 @Override
4258 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004259 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004260 final long ident = Binder.clearCallingIdentity();
4261 try {
4262 synchronized (mGlobalLock) {
4263 mStackSupervisor.setSplitScreenResizing(resizing);
4264 }
4265 } finally {
4266 Binder.restoreCallingIdentity(ident);
4267 }
4268 }
4269
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004270 /**
4271 * Check that we have the features required for VR-related API calls, and throw an exception if
4272 * not.
4273 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004274 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004275 if (!mContext.getPackageManager().hasSystemFeature(
4276 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4277 throw new UnsupportedOperationException("VR mode not supported on this device!");
4278 }
4279 }
4280
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 @Override
4282 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004283 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004284
4285 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4286
4287 ActivityRecord r;
4288 synchronized (mGlobalLock) {
4289 r = ActivityRecord.isInStackLocked(token);
4290 }
4291
4292 if (r == null) {
4293 throw new IllegalArgumentException();
4294 }
4295
4296 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004297 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 VrManagerInternal.NO_ERROR) {
4299 return err;
4300 }
4301
4302 // Clear the binder calling uid since this path may call moveToTask().
4303 final long callingId = Binder.clearCallingIdentity();
4304 try {
4305 synchronized (mGlobalLock) {
4306 r.requestedVrComponent = (enabled) ? packageName : null;
4307
4308 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004309 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004310 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 }
4312 return 0;
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(callingId);
4316 }
4317 }
4318
4319 @Override
4320 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4321 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4322 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004323 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004324 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4325 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4326 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004327 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 || activity.voiceSession != null) {
4329 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4330 return;
4331 }
4332 if (activity.pendingVoiceInteractionStart) {
4333 Slog.w(TAG, "Pending start of voice interaction already.");
4334 return;
4335 }
4336 activity.pendingVoiceInteractionStart = true;
4337 }
4338 LocalServices.getService(VoiceInteractionManagerInternal.class)
4339 .startLocalVoiceInteraction(callingActivity, options);
4340 }
4341
4342 @Override
4343 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4344 LocalServices.getService(VoiceInteractionManagerInternal.class)
4345 .stopLocalVoiceInteraction(callingActivity);
4346 }
4347
4348 @Override
4349 public boolean supportsLocalVoiceInteraction() {
4350 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4351 .supportsLocalVoiceInteraction();
4352 }
4353
4354 /** Notifies all listeners when the pinned stack animation starts. */
4355 @Override
4356 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004357 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004358 }
4359
4360 /** Notifies all listeners when the pinned stack animation ends. */
4361 @Override
4362 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004363 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 }
4365
4366 @Override
4367 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004368 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 final long ident = Binder.clearCallingIdentity();
4370 try {
4371 synchronized (mGlobalLock) {
4372 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4373 }
4374 } finally {
4375 Binder.restoreCallingIdentity(ident);
4376 }
4377 }
4378
4379 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004381 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382
4383 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004384 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004385 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 }
4388
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004390 final Message msg = PooledLambda.obtainMessage(
4391 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4392 DEFAULT_DISPLAY);
4393 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 }
4395
4396 final long origId = Binder.clearCallingIdentity();
4397 try {
4398 if (values != null) {
4399 Settings.System.clearConfiguration(values);
4400 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004401 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004402 UserHandle.USER_NULL, false /* deferResume */,
4403 mTmpUpdateConfigurationResult);
4404 return mTmpUpdateConfigurationResult.changes != 0;
4405 } finally {
4406 Binder.restoreCallingIdentity(origId);
4407 }
4408 }
4409 }
4410
4411 @Override
4412 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4413 CharSequence message) {
4414 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004415 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004416 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4417 }
4418 final long callingId = Binder.clearCallingIdentity();
4419 try {
4420 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004422 }
4423 } finally {
4424 Binder.restoreCallingIdentity(callingId);
4425 }
4426 }
4427
4428 @Override
4429 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004431 "cancelTaskWindowTransition()");
4432 final long ident = Binder.clearCallingIdentity();
4433 try {
4434 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004435 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 MATCH_TASK_IN_STACKS_ONLY);
4437 if (task == null) {
4438 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4439 return;
4440 }
4441 task.cancelWindowTransition();
4442 }
4443 } finally {
4444 Binder.restoreCallingIdentity(ident);
4445 }
4446 }
4447
4448 @Override
4449 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004451 final long ident = Binder.clearCallingIdentity();
4452 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004453 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 } finally {
4455 Binder.restoreCallingIdentity(ident);
4456 }
4457 }
4458
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004459 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4460 boolean restoreFromDisk) {
4461 final TaskRecord task;
4462 synchronized (mGlobalLock) {
4463 task = mRootActivityContainer.anyTaskForId(taskId,
4464 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4465 if (task == null) {
4466 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4467 return null;
4468 }
4469 }
4470 // Don't call this while holding the lock as this operation might hit the disk.
4471 return task.getSnapshot(reducedResolution, restoreFromDisk);
4472 }
4473
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004474 @Override
4475 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4476 synchronized (mGlobalLock) {
4477 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4478 if (r == null) {
4479 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4480 + token);
4481 return;
4482 }
4483 final long origId = Binder.clearCallingIdentity();
4484 try {
4485 r.setDisablePreviewScreenshots(disable);
4486 } finally {
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489 }
4490 }
4491
4492 /** Return the user id of the last resumed activity. */
4493 @Override
4494 public @UserIdInt
4495 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4498 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004499 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004502 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 }
4504 }
4505
4506 @Override
4507 public void updateLockTaskFeatures(int userId, int flags) {
4508 final int callingUid = Binder.getCallingUid();
4509 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 "updateLockTaskFeatures()");
4512 }
4513 synchronized (mGlobalLock) {
4514 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4515 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004516 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 return;
4526 }
4527 final long origId = Binder.clearCallingIdentity();
4528 try {
4529 r.setShowWhenLocked(showWhenLocked);
4530 } finally {
4531 Binder.restoreCallingIdentity(origId);
4532 }
4533 }
4534 }
4535
4536 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004537 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null) {
4541 return;
4542 }
4543 final long origId = Binder.clearCallingIdentity();
4544 try {
4545 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4546 } finally {
4547 Binder.restoreCallingIdentity(origId);
4548 }
4549 }
4550 }
4551
4552 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4554 synchronized (mGlobalLock) {
4555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4556 if (r == null) {
4557 return;
4558 }
4559 final long origId = Binder.clearCallingIdentity();
4560 try {
4561 r.setTurnScreenOn(turnScreenOn);
4562 } finally {
4563 Binder.restoreCallingIdentity(origId);
4564 }
4565 }
4566 }
4567
4568 @Override
4569 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004570 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004572 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 synchronized (mGlobalLock) {
4574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4575 if (r == null) {
4576 return;
4577 }
4578 final long origId = Binder.clearCallingIdentity();
4579 try {
4580 r.registerRemoteAnimations(definition);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
4588 public void registerRemoteAnimationForNextActivityStart(String packageName,
4589 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 "registerRemoteAnimationForNextActivityStart");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004592 adapter.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004593 synchronized (mGlobalLock) {
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004596 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 packageName, adapter);
4598 } finally {
4599 Binder.restoreCallingIdentity(origId);
4600 }
4601 }
4602 }
4603
Evan Rosky966759f2019-01-15 10:33:58 -08004604 @Override
4605 public void registerRemoteAnimationsForDisplay(int displayId,
4606 RemoteAnimationDefinition definition) {
4607 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4608 "registerRemoteAnimations");
Jorim Jaggi589c5ba2019-07-30 16:50:13 +02004609 definition.setCallingPidUid(Binder.getCallingPid(), Binder.getCallingUid());
Evan Rosky966759f2019-01-15 10:33:58 -08004610 synchronized (mGlobalLock) {
4611 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4612 if (display == null) {
4613 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 display.mDisplayContent.registerRemoteAnimations(definition);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004625 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4626 @Override
4627 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4628 synchronized (mGlobalLock) {
4629 final long origId = Binder.clearCallingIdentity();
4630 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004631 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 } finally {
4633 Binder.restoreCallingIdentity(origId);
4634 }
4635 }
4636 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004637
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004638 @Override
4639 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004642 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004643 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004644 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004645 }
4646 }
4647
4648 @Override
4649 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004651 != PERMISSION_GRANTED) {
4652 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4653 + Binder.getCallingPid()
4654 + ", uid=" + Binder.getCallingUid()
4655 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4656 Slog.w(TAG, msg);
4657 throw new SecurityException(msg);
4658 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004659 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004660 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004661 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004662 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004663 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 }
4665 }
4666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004667 @Override
4668 public void stopAppSwitches() {
4669 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4670 synchronized (mGlobalLock) {
4671 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004672 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004673 mDidAppSwitch = false;
4674 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4675 }
4676 }
4677
4678 @Override
4679 public void resumeAppSwitches() {
4680 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4681 synchronized (mGlobalLock) {
4682 // Note that we don't execute any pending app switches... we will
4683 // let those wait until either the timeout, or the next start
4684 // activity request.
4685 mAppSwitchesAllowedTime = 0;
4686 }
4687 }
4688
Ricky Wai906af482019-06-03 17:25:28 +01004689 long getLastStopAppSwitchesTime() {
4690 return mLastStopAppSwitchesTime;
4691 }
4692
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004693 void onStartActivitySetDidAppSwitch() {
4694 if (mDidAppSwitch) {
4695 // This is the second allowed switch since we stopped switches, so now just generally
4696 // allow switches. Use case:
4697 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4698 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4699 // anyone to switch again).
4700 mAppSwitchesAllowedTime = 0;
4701 } else {
4702 mDidAppSwitch = true;
4703 }
4704 }
4705
4706 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 boolean shouldDisableNonVrUiLocked() {
4708 return mVrController.shouldDisableNonVrUiLocked();
4709 }
4710
Wale Ogunwale53783742018-09-16 10:21:51 -07004711 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 // 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 +00004713 // itself, but isn't on the main display, then move it there before enabling VR Mode.
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004714 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
Wale Ogunwaleb8e6b632019-06-28 15:19:25 +00004715 Slog.i(TAG, "Moving " + r.shortComponentName + " from display " + r.getDisplayId()
4716 + " to main display for VR");
4717 mRootActivityContainer.moveStackToDisplay(
4718 r.getStackId(), DEFAULT_DISPLAY, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004719 }
4720 mH.post(() -> {
4721 if (!mVrController.onVrModeChanged(r)) {
4722 return;
4723 }
4724 synchronized (mGlobalLock) {
4725 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4726 mWindowManager.disableNonVrUi(disableNonVrUi);
4727 if (disableNonVrUi) {
4728 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4729 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004730 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732 }
4733 });
4734 }
4735
Wale Ogunwale53783742018-09-16 10:21:51 -07004736 @Override
4737 public int getPackageScreenCompatMode(String packageName) {
4738 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4739 synchronized (mGlobalLock) {
4740 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4741 }
4742 }
4743
4744 @Override
4745 public void setPackageScreenCompatMode(String packageName, int mode) {
4746 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4747 "setPackageScreenCompatMode");
4748 synchronized (mGlobalLock) {
4749 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4750 }
4751 }
4752
4753 @Override
4754 public boolean getPackageAskScreenCompat(String packageName) {
4755 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4756 synchronized (mGlobalLock) {
4757 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4758 }
4759 }
4760
4761 @Override
4762 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4763 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4764 "setPackageAskScreenCompat");
4765 synchronized (mGlobalLock) {
4766 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4767 }
4768 }
4769
Wale Ogunwale64258362018-10-16 15:13:37 -07004770 public static String relaunchReasonToString(int relaunchReason) {
4771 switch (relaunchReason) {
4772 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4773 return "window_resize";
4774 case RELAUNCH_REASON_FREE_RESIZE:
4775 return "free_resize";
4776 default:
4777 return null;
4778 }
4779 }
4780
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004781 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004782 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004783 }
4784
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004785 /** Pokes the task persister. */
4786 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4787 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4788 }
4789
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004790 boolean isKeyguardLocked() {
4791 return mKeyguardController.isKeyguardLocked();
4792 }
4793
Garfield Tan01548632018-11-27 10:15:48 -08004794 /**
4795 * Clears launch params for the given package.
4796 * @param packageNames the names of the packages of which the launch params are to be cleared
4797 */
4798 @Override
4799 public void clearLaunchParamsForPackages(List<String> packageNames) {
4800 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4801 "clearLaunchParamsForPackages");
4802 synchronized (mGlobalLock) {
4803 for (int i = 0; i < packageNames.size(); ++i) {
4804 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4805 }
4806 }
4807 }
4808
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004809 /**
4810 * Makes the display with the given id a single task instance display. I.e the display can only
4811 * contain one task.
4812 */
4813 @Override
4814 public void setDisplayToSingleTaskInstance(int displayId) {
4815 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4816 "setDisplayToSingleTaskInstance");
4817 final long origId = Binder.clearCallingIdentity();
4818 try {
4819 final ActivityDisplay display =
4820 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4821 if (display != null) {
4822 display.setDisplayToSingleTaskInstance();
4823 }
4824 } finally {
4825 Binder.restoreCallingIdentity(origId);
4826 }
4827 }
4828
Wale Ogunwale31913b52018-10-13 08:29:31 -07004829 void dumpLastANRLocked(PrintWriter pw) {
4830 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4831 if (mLastANRState == null) {
4832 pw.println(" <no ANR has occurred since boot>");
4833 } else {
4834 pw.println(mLastANRState);
4835 }
4836 }
4837
4838 void dumpLastANRTracesLocked(PrintWriter pw) {
4839 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4840
4841 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4842 if (ArrayUtils.isEmpty(files)) {
4843 pw.println(" <no ANR has occurred since boot>");
4844 return;
4845 }
4846 // Find the latest file.
4847 File latest = null;
4848 for (File f : files) {
4849 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4850 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004851 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004852 }
4853 pw.print("File: ");
4854 pw.print(latest.getName());
4855 pw.println();
4856 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4857 String line;
4858 while ((line = in.readLine()) != null) {
4859 pw.println(line);
4860 }
4861 } catch (IOException e) {
4862 pw.print("Unable to read: ");
4863 pw.print(e);
4864 pw.println();
4865 }
4866 }
4867
4868 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4869 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4870 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4871 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4872 }
4873
4874 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4875 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4876 pw.println(header);
4877
Wale Ogunwaled32da472018-11-16 07:19:28 -08004878 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004879 dumpPackage);
4880 boolean needSep = printedAnything;
4881
4882 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004883 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004884 " ResumedActivity: ");
4885 if (printed) {
4886 printedAnything = true;
4887 needSep = false;
4888 }
4889
4890 if (dumpPackage == null) {
4891 if (needSep) {
4892 pw.println();
4893 }
4894 printedAnything = true;
4895 mStackSupervisor.dump(pw, " ");
4896 }
4897
4898 if (!printedAnything) {
4899 pw.println(" (nothing)");
4900 }
4901 }
4902
4903 void dumpActivityContainersLocked(PrintWriter pw) {
Jeff Changde322732019-07-12 12:16:23 +08004904 pw.println("ACTIVITY MANAGER CONTAINERS (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004905 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004906 pw.println(" ");
4907 }
4908
4909 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4910 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4911 getActivityStartController().dump(pw, "", dumpPackage);
4912 }
4913
4914 /**
4915 * There are three things that cmd can be:
4916 * - a flattened component name that matches an existing activity
4917 * - the cmd arg isn't the flattened component name of an existing activity:
4918 * dump all activity whose component contains the cmd as a substring
4919 * - A hex number of the ActivityRecord object instance.
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004920 * <p>
4921 * The caller should not hold lock when calling this method because it will wait for the
4922 * activities to complete the dump.
Wale Ogunwale31913b52018-10-13 08:29:31 -07004923 *
4924 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4925 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4926 */
4927 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4928 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4929 ArrayList<ActivityRecord> activities;
4930
4931 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004932 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004933 dumpFocusedStackOnly);
4934 }
4935
4936 if (activities.size() <= 0) {
4937 return false;
4938 }
4939
4940 String[] newArgs = new String[args.length - opti];
4941 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4942
4943 TaskRecord lastTask = null;
4944 boolean needSep = false;
4945 for (int i = activities.size() - 1; i >= 0; i--) {
4946 ActivityRecord r = activities.get(i);
4947 if (needSep) {
4948 pw.println();
4949 }
4950 needSep = true;
4951 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004952 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004953 if (lastTask != task) {
4954 lastTask = task;
4955 pw.print("TASK "); pw.print(lastTask.affinity);
4956 pw.print(" id="); pw.print(lastTask.taskId);
4957 pw.print(" userId="); pw.println(lastTask.userId);
4958 if (dumpAll) {
4959 lastTask.dump(pw, " ");
4960 }
4961 }
4962 }
4963 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4964 }
4965 return true;
4966 }
4967
4968 /**
4969 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4970 * there is a thread associated with the activity.
4971 */
4972 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4973 final ActivityRecord r, String[] args, boolean dumpAll) {
4974 String innerPrefix = prefix + " ";
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004975 IApplicationThread appThread = null;
Wale Ogunwale31913b52018-10-13 08:29:31 -07004976 synchronized (mGlobalLock) {
4977 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4978 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4979 pw.print(" pid=");
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004980 if (r.hasProcess()) {
4981 pw.println(r.app.getPid());
4982 appThread = r.app.getThread();
4983 } else {
4984 pw.println("(not running)");
4985 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004986 if (dumpAll) {
4987 r.dump(pw, innerPrefix);
4988 }
4989 }
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004990 if (appThread != null) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07004991 // flush anything that is already in the PrintWriter since the thread is going
4992 // to write to the file descriptor directly
4993 pw.flush();
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08004994 try (TransferPipe tp = new TransferPipe()) {
4995 appThread.dumpActivity(tp.getWriteFd(), r.appToken, innerPrefix, args);
4996 tp.go(fd);
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 } catch (IOException e) {
4998 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4999 } catch (RemoteException e) {
5000 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5001 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005002 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005003 }
5004
sanryhuang498e77e2018-12-06 14:57:01 +08005005 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5006 boolean testPssMode) {
5007 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5008 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5009 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005010 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005011 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5012 st.toString());
5013 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5016 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005017 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5018 testPssMode);
5019 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005020 }
5021
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005022 int getCurrentUserId() {
5023 return mAmInternal.getCurrentUserId();
5024 }
5025
5026 private void enforceNotIsolatedCaller(String caller) {
5027 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5028 throw new SecurityException("Isolated process not allowed to call " + caller);
5029 }
5030 }
5031
Wale Ogunwalef6733932018-06-27 05:14:34 -07005032 public Configuration getConfiguration() {
5033 Configuration ci;
5034 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005035 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005036 ci.userSetLocale = false;
5037 }
5038 return ci;
5039 }
5040
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005041 /**
5042 * Current global configuration information. Contains general settings for the entire system,
5043 * also corresponds to the merged configuration of the default display.
5044 */
5045 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005046 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005047 }
5048
5049 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5050 boolean initLocale) {
5051 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5052 }
5053
5054 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5055 boolean initLocale, boolean deferResume) {
5056 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5057 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5058 UserHandle.USER_NULL, deferResume);
5059 }
5060
Wale Ogunwale59507092018-10-29 09:00:30 -07005061 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005062 final long origId = Binder.clearCallingIdentity();
5063 try {
5064 synchronized (mGlobalLock) {
5065 updateConfigurationLocked(values, null, false, true, userId,
5066 false /* deferResume */);
5067 }
5068 } finally {
5069 Binder.restoreCallingIdentity(origId);
5070 }
5071 }
5072
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5074 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5075 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5076 deferResume, null /* result */);
5077 }
5078
5079 /**
5080 * Do either or both things: (1) change the current configuration, and (2)
5081 * make sure the given activity is running with the (now) current
5082 * configuration. Returns true if the activity has been left running, or
5083 * false if <var>starting</var> is being destroyed to match the new
5084 * configuration.
5085 *
5086 * @param userId is only used when persistent parameter is set to true to persist configuration
5087 * for that particular user
5088 */
5089 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5090 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5091 ActivityTaskManagerService.UpdateConfigurationResult result) {
5092 int changes = 0;
5093 boolean kept = true;
5094
5095 if (mWindowManager != null) {
5096 mWindowManager.deferSurfaceLayout();
5097 }
5098 try {
5099 if (values != null) {
5100 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5101 deferResume);
5102 }
5103
5104 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5105 } finally {
5106 if (mWindowManager != null) {
5107 mWindowManager.continueSurfaceLayout();
5108 }
5109 }
5110
5111 if (result != null) {
5112 result.changes = changes;
5113 result.activityRelaunched = !kept;
5114 }
5115 return kept;
5116 }
5117
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005118 /** Update default (global) configuration and notify listeners about changes. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005119 int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005120 boolean persistent, int userId, boolean deferResume) {
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005121
5122 final ActivityDisplay defaultDisplay =
5123 mRootActivityContainer.getActivityDisplay(DEFAULT_DISPLAY);
5124
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005125 mTempConfig.setTo(getGlobalConfiguration());
5126 final int changes = mTempConfig.updateFrom(values);
5127 if (changes == 0) {
5128 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5129 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5130 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5131 // (even if there are no actual changes) to unfreeze the window.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005132 defaultDisplay.performDisplayOverrideConfigUpdate(values, deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005133 return 0;
5134 }
5135
5136 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5137 "Updating global configuration to: " + values);
5138
5139 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5140 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5141 values.colorMode,
5142 values.densityDpi,
5143 values.fontScale,
5144 values.hardKeyboardHidden,
5145 values.keyboard,
5146 values.keyboardHidden,
5147 values.mcc,
5148 values.mnc,
5149 values.navigation,
5150 values.navigationHidden,
5151 values.orientation,
5152 values.screenHeightDp,
5153 values.screenLayout,
5154 values.screenWidthDp,
5155 values.smallestScreenWidthDp,
5156 values.touchscreen,
5157 values.uiMode);
5158
5159
5160 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5161 final LocaleList locales = values.getLocales();
5162 int bestLocaleIndex = 0;
5163 if (locales.size() > 1) {
5164 if (mSupportedSystemLocales == null) {
5165 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5166 }
5167 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5168 }
5169 SystemProperties.set("persist.sys.locale",
5170 locales.get(bestLocaleIndex).toLanguageTag());
5171 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005172
5173 final Message m = PooledLambda.obtainMessage(
5174 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5175 locales.get(bestLocaleIndex));
5176 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177 }
5178
Yunfan Chen75157d72018-07-27 14:47:21 +09005179 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180
5181 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005182 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183
5184 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5185 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005186 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005189 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190
5191 AttributeCache ac = AttributeCache.instance();
5192 if (ac != null) {
5193 ac.updateConfiguration(mTempConfig);
5194 }
5195
5196 // Make sure all resources in our process are updated right now, so that anyone who is going
5197 // to retrieve resource values after we return will be sure to get the new ones. This is
5198 // especially important during boot, where the first config change needs to guarantee all
5199 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005200 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005201
5202 // We need another copy of global config because we're scheduling some calls instead of
5203 // running them in place. We need to be sure that object we send will be handled unchanged.
5204 final Configuration configCopy = new Configuration(mTempConfig);
5205 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005206 final Message msg = PooledLambda.obtainMessage(
5207 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5208 this, userId, configCopy);
5209 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 }
5211
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005212 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5213 for (int i = pidMap.size() - 1; i >= 0; i--) {
5214 final int pid = pidMap.keyAt(i);
5215 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005216 if (DEBUG_CONFIGURATION) {
5217 Slog.v(TAG_CONFIGURATION, "Update process config of "
5218 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005220 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221 }
5222
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005223 final Message msg = PooledLambda.obtainMessage(
5224 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5225 mAmInternal, changes, initLocale);
5226 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227
5228 // Override configuration of the default display duplicates global config, so we need to
5229 // update it also. This will also notify WindowManager about changes.
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005230 defaultDisplay.performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(),
5231 deferResume);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005232
5233 return changes;
5234 }
5235
Wale Ogunwalef6733932018-06-27 05:14:34 -07005236 private void updateEventDispatchingLocked(boolean booted) {
5237 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5238 }
5239
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005240 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5241 final ContentResolver resolver = mContext.getContentResolver();
5242 Settings.System.putConfigurationForUser(resolver, config, userId);
5243 }
5244
5245 private void sendLocaleToMountDaemonMsg(Locale l) {
5246 try {
5247 IBinder service = ServiceManager.getService("mount");
5248 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5249 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5250 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5251 } catch (RemoteException e) {
5252 Log.e(TAG, "Error storing locale for decryption UI", e);
5253 }
5254 }
5255
Alison Cichowlas3e340502018-08-07 17:15:01 -04005256 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5257 mStartActivitySources.remove(permissionToken);
5258 mExpiredStartAsCallerTokens.add(permissionToken);
5259 }
5260
5261 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5262 mExpiredStartAsCallerTokens.remove(permissionToken);
5263 }
5264
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005265 boolean isActivityStartsLoggingEnabled() {
5266 return mAmInternal.isActivityStartsLoggingEnabled();
5267 }
5268
Michal Karpinski8596ded2018-11-14 14:43:48 +00005269 boolean isBackgroundActivityStartsEnabled() {
5270 return mAmInternal.isBackgroundActivityStartsEnabled();
5271 }
5272
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 void enableScreenAfterBoot(boolean booted) {
5274 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5275 SystemClock.uptimeMillis());
5276 mWindowManager.enableScreenAfterBoot();
5277
5278 synchronized (mGlobalLock) {
5279 updateEventDispatchingLocked(booted);
5280 }
5281 }
5282
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005283 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5284 if (r == null || !r.hasProcess()) {
5285 return KEY_DISPATCHING_TIMEOUT_MS;
5286 }
5287 return getInputDispatchingTimeoutLocked(r.app);
5288 }
5289
5290 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005291 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005292 }
5293
Wale Ogunwalef6733932018-06-27 05:14:34 -07005294 /**
5295 * Decide based on the configuration whether we should show the ANR,
5296 * crash, etc dialogs. The idea is that if there is no affordance to
5297 * press the on-screen buttons, or the user experience would be more
5298 * greatly impacted than the crash itself, we shouldn't show the dialog.
5299 *
5300 * A thought: SystemUI might also want to get told about this, the Power
5301 * dialog / global actions also might want different behaviors.
5302 */
5303 private void updateShouldShowDialogsLocked(Configuration config) {
5304 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5305 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5306 && config.navigation == Configuration.NAVIGATION_NONAV);
5307 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5308 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5309 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5310 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5311 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5312 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5313 HIDE_ERROR_DIALOGS, 0) != 0;
5314 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5315 }
5316
5317 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5318 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5319 FONT_SCALE, 1.0f, userId);
5320
5321 synchronized (this) {
5322 if (getGlobalConfiguration().fontScale == scaleFactor) {
5323 return;
5324 }
5325
5326 final Configuration configuration
5327 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5328 configuration.fontScale = scaleFactor;
5329 updatePersistentConfiguration(configuration, userId);
5330 }
5331 }
5332
5333 // Actually is sleeping or shutting down or whatever else in the future
5334 // is an inactive state.
5335 boolean isSleepingOrShuttingDownLocked() {
5336 return isSleepingLocked() || mShuttingDown;
5337 }
5338
5339 boolean isSleepingLocked() {
5340 return mSleeping;
5341 }
5342
Riddle Hsu16567132018-08-16 21:37:47 +08005343 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005344 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005345 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005346 if (task.isActivityTypeStandard()) {
5347 if (mCurAppTimeTracker != r.appTimeTracker) {
5348 // We are switching app tracking. Complete the current one.
5349 if (mCurAppTimeTracker != null) {
5350 mCurAppTimeTracker.stop();
5351 mH.obtainMessage(
5352 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005353 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005354 mCurAppTimeTracker = null;
5355 }
5356 if (r.appTimeTracker != null) {
5357 mCurAppTimeTracker = r.appTimeTracker;
5358 startTimeTrackingFocusedActivityLocked();
5359 }
5360 } else {
5361 startTimeTrackingFocusedActivityLocked();
5362 }
5363 } else {
5364 r.appTimeTracker = null;
5365 }
5366 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5367 // TODO: Probably not, because we don't want to resume voice on switching
5368 // back to this activity
5369 if (task.voiceInteractor != null) {
5370 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5371 } else {
5372 finishRunningVoiceLocked();
5373
5374 if (mLastResumedActivity != null) {
5375 final IVoiceInteractionSession session;
5376
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005377 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005378 if (lastResumedActivityTask != null
5379 && lastResumedActivityTask.voiceSession != null) {
5380 session = lastResumedActivityTask.voiceSession;
5381 } else {
5382 session = mLastResumedActivity.voiceSession;
5383 }
5384
5385 if (session != null) {
5386 // We had been in a voice interaction session, but now focused has
5387 // move to something different. Just finish the session, we can't
5388 // return to it and retain the proper state and synchronization with
5389 // the voice interaction service.
5390 finishVoiceTask(session);
5391 }
5392 }
5393 }
5394
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005395 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5396 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005397 }
5398 updateResumedAppTrace(r);
5399 mLastResumedActivity = r;
5400
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005401 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005402
5403 applyUpdateLockStateLocked(r);
5404 applyUpdateVrModeLocked(r);
5405
5406 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005407 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005408 r == null ? "NULL" : r.shortComponentName,
5409 reason);
5410 }
5411
5412 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5413 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005414 final ActivityTaskManagerInternal.SleepToken token =
5415 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 updateSleepIfNeededLocked();
5417 return token;
5418 }
5419 }
5420
5421 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005422 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005423 final boolean wasSleeping = mSleeping;
5424 boolean updateOomAdj = false;
5425
5426 if (!shouldSleep) {
5427 // If wasSleeping is true, we need to wake up activity manager state from when
5428 // we started sleeping. In either case, we need to apply the sleep tokens, which
5429 // will wake up stacks or put them to sleep as appropriate.
5430 if (wasSleeping) {
5431 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005432 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5433 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005434 startTimeTrackingFocusedActivityLocked();
5435 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005436 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005437 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5438 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005439 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005440 if (wasSleeping) {
5441 updateOomAdj = true;
5442 }
5443 } else if (!mSleeping && shouldSleep) {
5444 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005445 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5446 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005447 if (mCurAppTimeTracker != null) {
5448 mCurAppTimeTracker.stop();
5449 }
5450 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005451 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005452 mStackSupervisor.goingToSleepLocked();
5453 updateResumedAppTrace(null /* resumed */);
5454 updateOomAdj = true;
5455 }
5456 if (updateOomAdj) {
wilsonshih8d096d22019-08-01 17:46:14 +08005457 updateOomAdj();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005458 }
5459 }
5460
5461 void updateOomAdj() {
5462 mH.post(mAmInternal::updateOomAdj);
5463 }
5464
Wale Ogunwale53783742018-09-16 10:21:51 -07005465 void updateCpuStats() {
5466 mH.post(mAmInternal::updateCpuStats);
5467 }
5468
Hui Yu03d12402018-12-06 18:00:37 -08005469 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5470 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005471 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5472 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005473 mH.sendMessage(m);
5474 }
5475
Hui Yu03d12402018-12-06 18:00:37 -08005476 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005477 ComponentName taskRoot = null;
5478 final TaskRecord task = activity.getTaskRecord();
5479 if (task != null) {
5480 final ActivityRecord rootActivity = task.getRootActivity();
5481 if (rootActivity != null) {
5482 taskRoot = rootActivity.mActivityComponent;
5483 }
5484 }
5485
Hui Yu03d12402018-12-06 18:00:37 -08005486 final Message m = PooledLambda.obtainMessage(
5487 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005488 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005489 mH.sendMessage(m);
5490 }
5491
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005492 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5493 String hostingType) {
5494 try {
5495 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5496 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5497 + activity.processName);
5498 }
5499 // Post message to start process to avoid possible deadlock of calling into AMS with the
5500 // ATMS lock held.
5501 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5502 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5503 isTop, hostingType, activity.intent.getComponent());
5504 mH.sendMessage(m);
5505 } finally {
5506 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5507 }
5508 }
5509
Wale Ogunwale53783742018-09-16 10:21:51 -07005510 void setBooting(boolean booting) {
5511 mAmInternal.setBooting(booting);
5512 }
5513
5514 boolean isBooting() {
5515 return mAmInternal.isBooting();
5516 }
5517
5518 void setBooted(boolean booted) {
5519 mAmInternal.setBooted(booted);
5520 }
5521
5522 boolean isBooted() {
5523 return mAmInternal.isBooted();
5524 }
5525
5526 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5527 mH.post(() -> {
5528 if (finishBooting) {
5529 mAmInternal.finishBooting();
5530 }
5531 if (enableScreen) {
5532 mInternal.enableScreenAfterBoot(isBooted());
5533 }
5534 });
5535 }
5536
5537 void setHeavyWeightProcess(ActivityRecord root) {
5538 mHeavyWeightProcess = root.app;
5539 final Message m = PooledLambda.obtainMessage(
5540 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005542 mH.sendMessage(m);
5543 }
5544
5545 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5546 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5547 return;
5548 }
5549
5550 mHeavyWeightProcess = null;
5551 final Message m = PooledLambda.obtainMessage(
5552 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5553 proc.mUserId);
5554 mH.sendMessage(m);
5555 }
5556
5557 private void cancelHeavyWeightProcessNotification(int userId) {
5558 final INotificationManager inm = NotificationManager.getService();
5559 if (inm == null) {
5560 return;
5561 }
5562 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005563 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005564 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5565 } catch (RuntimeException e) {
5566 Slog.w(TAG, "Error canceling notification for service", e);
5567 } catch (RemoteException e) {
5568 }
5569
5570 }
5571
5572 private void postHeavyWeightProcessNotification(
5573 WindowProcessController proc, Intent intent, int userId) {
5574 if (proc == null) {
5575 return;
5576 }
5577
5578 final INotificationManager inm = NotificationManager.getService();
5579 if (inm == null) {
5580 return;
5581 }
5582
5583 try {
5584 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5585 String text = mContext.getString(R.string.heavy_weight_notification,
5586 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5587 Notification notification =
5588 new Notification.Builder(context,
5589 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5590 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5591 .setWhen(0)
5592 .setOngoing(true)
5593 .setTicker(text)
5594 .setColor(mContext.getColor(
5595 com.android.internal.R.color.system_notification_accent_color))
5596 .setContentTitle(text)
5597 .setContentText(
5598 mContext.getText(R.string.heavy_weight_notification_detail))
5599 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5600 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5601 new UserHandle(userId)))
5602 .build();
5603 try {
5604 inm.enqueueNotificationWithTag("android", "android", null,
5605 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5606 } catch (RuntimeException e) {
5607 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5608 } catch (RemoteException e) {
5609 }
5610 } catch (PackageManager.NameNotFoundException e) {
5611 Slog.w(TAG, "Unable to create context for heavy notification", e);
5612 }
5613
5614 }
5615
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005616 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5617 IBinder token, String resultWho, int requestCode, Intent[] intents,
5618 String[] resolvedTypes, int flags, Bundle bOptions) {
5619
5620 ActivityRecord activity = null;
5621 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5622 activity = ActivityRecord.isInStackLocked(token);
5623 if (activity == null) {
5624 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5625 return null;
5626 }
5627 if (activity.finishing) {
5628 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5629 return null;
5630 }
5631 }
5632
5633 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5634 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5635 bOptions);
5636 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5637 if (noCreate) {
5638 return rec;
5639 }
5640 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5641 if (activity.pendingResults == null) {
5642 activity.pendingResults = new HashSet<>();
5643 }
5644 activity.pendingResults.add(rec.ref);
5645 }
5646 return rec;
5647 }
5648
Andrii Kulian52d255c2018-07-13 11:32:19 -07005649 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005650 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005651 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005652 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5653 mCurAppTimeTracker.start(resumedActivity.packageName);
5654 }
5655 }
5656
5657 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5658 if (mTracedResumedActivity != null) {
5659 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5660 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5661 }
5662 if (resumed != null) {
5663 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5664 constructResumedTraceName(resumed.packageName), 0);
5665 }
5666 mTracedResumedActivity = resumed;
5667 }
5668
5669 private String constructResumedTraceName(String packageName) {
5670 return "focused app: " + packageName;
5671 }
5672
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005673 /** Applies latest configuration and/or visibility updates if needed. */
Shivam Agrawal1d3db652019-07-01 15:26:11 -07005674 boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005675 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005676 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005677 // mainStack is null during startup.
5678 if (mainStack != null) {
5679 if (changes != 0 && starting == null) {
5680 // If the configuration changed, and the caller is not already
5681 // in the process of starting an activity, then find the top
5682 // activity to check if its configuration needs to change.
5683 starting = mainStack.topRunningActivityLocked();
5684 }
5685
5686 if (starting != null) {
5687 kept = starting.ensureActivityConfiguration(changes,
5688 false /* preserveWindow */);
5689 // And we need to make sure at this point that all other activities
5690 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005691 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005692 !PRESERVE_WINDOWS);
5693 }
5694 }
5695
5696 return kept;
5697 }
5698
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005699 void scheduleAppGcsLocked() {
5700 mH.post(() -> mAmInternal.scheduleAppGcs());
5701 }
5702
Wale Ogunwale53783742018-09-16 10:21:51 -07005703 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5704 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5705 }
5706
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005707 /**
5708 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5709 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5710 * on demand.
5711 */
5712 IPackageManager getPackageManager() {
5713 return AppGlobals.getPackageManager();
5714 }
5715
5716 PackageManagerInternal getPackageManagerInternalLocked() {
5717 if (mPmInternal == null) {
5718 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5719 }
5720 return mPmInternal;
5721 }
5722
Hai Zhangf4da9be2019-05-01 13:46:06 +08005723 PermissionPolicyInternal getPermissionPolicyInternal() {
5724 if (mPermissionPolicyInternal == null) {
5725 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5726 }
5727 return mPermissionPolicyInternal;
5728 }
5729
Wale Ogunwale008163e2018-07-23 23:11:08 -07005730 AppWarnings getAppWarningsLocked() {
5731 return mAppWarnings;
5732 }
5733
Wale Ogunwale214f3482018-10-04 11:00:47 -07005734 Intent getHomeIntent() {
5735 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5736 intent.setComponent(mTopComponent);
5737 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5738 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5739 intent.addCategory(Intent.CATEGORY_HOME);
5740 }
5741 return intent;
5742 }
5743
Chilun2ef71f72018-11-16 17:57:15 +08005744 /**
5745 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5746 * activities.
5747 *
5748 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5749 * component defined in config_secondaryHomeComponent.
5750 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5751 */
5752 Intent getSecondaryHomeIntent(String preferredPackage) {
5753 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005754 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5755 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5756 if (preferredPackage == null || useSystemProvidedLauncher) {
5757 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005758 final String secondaryHomeComponent = mContext.getResources().getString(
5759 com.android.internal.R.string.config_secondaryHomeComponent);
5760 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5761 } else {
5762 intent.setPackage(preferredPackage);
5763 }
5764 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5765 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5766 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5767 }
5768 return intent;
5769 }
5770
Wale Ogunwale214f3482018-10-04 11:00:47 -07005771 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5772 if (info == null) return null;
5773 ApplicationInfo newInfo = new ApplicationInfo(info);
5774 newInfo.initForUser(userId);
5775 return newInfo;
5776 }
5777
Wale Ogunwale9c103022018-10-18 07:44:54 -07005778 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005779 if (uid == SYSTEM_UID) {
5780 // The system gets to run in any process. If there are multiple processes with the same
5781 // uid, just pick the first (this should never happen).
5782 final SparseArray<WindowProcessController> procs =
5783 mProcessNames.getMap().get(processName);
5784 if (procs == null) return null;
5785 final int procCount = procs.size();
5786 for (int i = 0; i < procCount; i++) {
5787 final int procUid = procs.keyAt(i);
5788 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5789 // Don't use an app process or different user process for system component.
5790 continue;
5791 }
5792 return procs.valueAt(i);
5793 }
5794 }
5795
5796 return mProcessNames.get(processName, uid);
5797 }
5798
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005799 WindowProcessController getProcessController(IApplicationThread thread) {
5800 if (thread == null) {
5801 return null;
5802 }
5803
5804 final IBinder threadBinder = thread.asBinder();
5805 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5806 for (int i = pmap.size()-1; i >= 0; i--) {
5807 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5808 for (int j = procs.size() - 1; j >= 0; j--) {
5809 final WindowProcessController proc = procs.valueAt(j);
5810 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5811 return proc;
5812 }
5813 }
5814 }
5815
5816 return null;
5817 }
5818
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005819 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005820 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005821 if (proc == null) return null;
5822 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5823 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005824 }
5825 return null;
5826 }
5827
Riddle Hsua0536432019-02-16 00:38:59 +08005828 int getUidState(int uid) {
5829 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005830 }
5831
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005832 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005833 // A uid is considered to be foreground if it has a visible non-toast window.
5834 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005835 }
5836
Ricky Wai96f5c352019-04-10 18:40:17 +01005837 boolean isDeviceOwner(int uid) {
5838 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005839 }
5840
Ricky Wai96f5c352019-04-10 18:40:17 +01005841 void setDeviceOwnerUid(int uid) {
5842 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005843 }
5844
Wale Ogunwale9de19442018-10-18 19:05:03 -07005845 /**
5846 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5847 * the whitelist
5848 */
5849 String getPendingTempWhitelistTagForUidLocked(int uid) {
5850 return mPendingTempWhitelist.get(uid);
5851 }
5852
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005853 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5854 if (true || Build.IS_USER) {
5855 return;
5856 }
5857
5858 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5859 StrictMode.allowThreadDiskWrites();
5860 try {
5861 File tracesDir = new File("/data/anr");
5862 File tracesFile = null;
5863 try {
5864 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5865
5866 StringBuilder sb = new StringBuilder();
Neil Fuller97746812019-08-19 14:20:50 +01005867 String timeString =
5868 TimeMigrationUtils.formatMillisWithFixedFormat(System.currentTimeMillis());
5869 sb.append(timeString);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005870 sb.append(": ");
5871 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5872 sb.append(" since ");
5873 sb.append(msg);
5874 FileOutputStream fos = new FileOutputStream(tracesFile);
5875 fos.write(sb.toString().getBytes());
5876 if (app == null) {
5877 fos.write("\n*** No application process!".getBytes());
5878 }
5879 fos.close();
5880 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5881 } catch (IOException e) {
5882 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5883 return;
5884 }
5885
5886 if (app != null && app.getPid() > 0) {
5887 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5888 firstPids.add(app.getPid());
5889 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5890 }
5891
5892 File lastTracesFile = null;
5893 File curTracesFile = null;
5894 for (int i=9; i>=0; i--) {
5895 String name = String.format(Locale.US, "slow%02d.txt", i);
5896 curTracesFile = new File(tracesDir, name);
5897 if (curTracesFile.exists()) {
5898 if (lastTracesFile != null) {
5899 curTracesFile.renameTo(lastTracesFile);
5900 } else {
5901 curTracesFile.delete();
5902 }
5903 }
5904 lastTracesFile = curTracesFile;
5905 }
5906 tracesFile.renameTo(curTracesFile);
5907 } finally {
5908 StrictMode.setThreadPolicy(oldPolicy);
5909 }
5910 }
5911
Michal Karpinskida34cd42019-04-02 19:46:52 +01005912 boolean isAssociatedCompanionApp(int userId, int uid) {
5913 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5914 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005915 return false;
5916 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005917 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005918 }
5919
Issei Suzuki734bc942019-06-05 13:59:52 +02005920 void notifySingleTaskDisplayEmpty(int displayId) {
5921 mTaskChangeNotificationController.notifySingleTaskDisplayEmpty(displayId);
5922 }
5923
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005924 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005925 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005926
5927
Wale Ogunwale98875612018-10-12 07:53:02 -07005928 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5929 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005930
Riddle Hsud93a6c42018-11-29 21:50:06 +08005931 H(Looper looper) {
5932 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005933 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005934
5935 @Override
5936 public void handleMessage(Message msg) {
5937 switch (msg.what) {
5938 case REPORT_TIME_TRACKER_MSG: {
5939 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5940 tracker.deliverResult(mContext);
5941 } break;
5942 }
5943 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005944 }
5945
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005946 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005947 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005948
5949 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005950 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005951 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005952
5953 @Override
5954 public void handleMessage(Message msg) {
5955 switch (msg.what) {
5956 case DISMISS_DIALOG_UI_MSG: {
5957 final Dialog d = (Dialog) msg.obj;
5958 d.dismiss();
5959 break;
5960 }
5961 }
5962 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005963 }
5964
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 final class LocalService extends ActivityTaskManagerInternal {
5966 @Override
5967 public SleepToken acquireSleepToken(String tag, int displayId) {
5968 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005969 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005970 }
5971
5972 @Override
5973 public ComponentName getHomeActivityForUser(int userId) {
5974 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005975 final ActivityRecord homeActivity =
5976 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005977 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005978 }
5979 }
5980
5981 @Override
5982 public void onLocalVoiceInteractionStarted(IBinder activity,
5983 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5984 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005985 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005986 }
5987 }
5988
5989 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005990 public void notifyAppTransitionStarting(SparseIntArray reasons,
5991 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005992 synchronized (mGlobalLock) {
5993 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5994 reasons, timestamp);
5995 }
5996 }
5997
5998 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02005999 public void notifySingleTaskDisplayDrawn(int displayId) {
6000 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6001 }
6002
6003 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006004 public void notifyAppTransitionFinished() {
6005 synchronized (mGlobalLock) {
6006 mStackSupervisor.notifyAppTransitionDone();
6007 }
6008 }
6009
6010 @Override
6011 public void notifyAppTransitionCancelled() {
6012 synchronized (mGlobalLock) {
6013 mStackSupervisor.notifyAppTransitionDone();
6014 }
6015 }
6016
6017 @Override
6018 public List<IBinder> getTopVisibleActivities() {
6019 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006020 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006021 }
6022 }
6023
6024 @Override
6025 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6026 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006027 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006028 }
6029 }
6030
6031 @Override
6032 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6033 Bundle bOptions) {
6034 Preconditions.checkNotNull(intents, "intents");
6035 final String[] resolvedTypes = new String[intents.length];
6036
6037 // UID of the package on user userId.
6038 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6039 // packageUid may not be initialized.
6040 int packageUid = 0;
6041 final long ident = Binder.clearCallingIdentity();
6042
6043 try {
6044 for (int i = 0; i < intents.length; i++) {
6045 resolvedTypes[i] =
6046 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6047 }
6048
6049 packageUid = AppGlobals.getPackageManager().getPackageUid(
6050 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6051 } catch (RemoteException e) {
6052 // Shouldn't happen.
6053 } finally {
6054 Binder.restoreCallingIdentity(ident);
6055 }
6056
Riddle Hsu591bf612019-02-14 17:55:31 +08006057 return getActivityStartController().startActivitiesInPackage(
6058 packageUid, packageName,
6059 intents, resolvedTypes, null /* resultTo */,
6060 SafeActivityOptions.fromBundle(bOptions), userId,
6061 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6062 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006063 }
6064
6065 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006066 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6067 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6068 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6069 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006070 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006071 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006072 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6073 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6074 userId, validateIncomingUser, originatingPendingIntent,
6075 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006076 }
6077 }
6078
6079 @Override
6080 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6081 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6082 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6083 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006084 PendingIntentRecord originatingPendingIntent,
6085 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006086 synchronized (mGlobalLock) {
6087 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6088 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6089 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006090 validateIncomingUser, originatingPendingIntent,
6091 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006092 }
6093 }
6094
6095 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006096 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6097 Intent intent, Bundle options, int userId) {
6098 return ActivityTaskManagerService.this.startActivityAsUser(
6099 caller, callerPacakge, intent,
6100 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6101 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6102 false /*validateIncomingUser*/);
6103 }
6104
6105 @Override
lumark588a3e82018-07-20 18:53:54 +08006106 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006107 synchronized (mGlobalLock) {
6108
6109 // We might change the visibilities here, so prepare an empty app transition which
6110 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006111 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006112 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006113 if (activityDisplay == null) {
6114 return;
6115 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006116 final DisplayContent dc = activityDisplay.mDisplayContent;
6117 final boolean wasTransitionSet =
6118 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006120 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006121 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006122 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006123
6124 // If there was a transition set already we don't want to interfere with it as we
6125 // might be starting it too early.
6126 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006127 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 }
6129 }
6130 if (callback != null) {
6131 callback.run();
6132 }
6133 }
6134
6135 @Override
6136 public void notifyKeyguardTrustedChanged() {
6137 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006138 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006139 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006140 }
6141 }
6142 }
6143
6144 /**
6145 * Called after virtual display Id is updated by
6146 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6147 * {@param vrVr2dDisplayId}.
6148 */
6149 @Override
6150 public void setVr2dDisplayId(int vr2dDisplayId) {
6151 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006153 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 }
6155 }
6156
6157 @Override
6158 public void setFocusedActivity(IBinder token) {
6159 synchronized (mGlobalLock) {
6160 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6161 if (r == null) {
6162 throw new IllegalArgumentException(
6163 "setFocusedActivity: No activity record matching token=" + token);
6164 }
Louis Chang19443452018-10-09 12:10:21 +08006165 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006166 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006167 }
6168 }
6169 }
6170
6171 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006172 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006173 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 }
6175
6176 @Override
6177 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006178 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006179 }
6180
6181 @Override
6182 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006183 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006184 }
6185
6186 @Override
6187 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6188 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6189 }
6190
6191 @Override
6192 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006193 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006194 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006195
6196 @Override
6197 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6198 synchronized (mGlobalLock) {
6199 mActiveVoiceInteractionServiceComponent = component;
6200 }
6201 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006202
6203 @Override
6204 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6205 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6206 return;
6207 }
6208 synchronized (mGlobalLock) {
6209 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6210 if (types == null) {
6211 if (uid < 0) {
6212 return;
6213 }
6214 types = new ArrayMap<>();
6215 mAllowAppSwitchUids.put(userId, types);
6216 }
6217 if (uid < 0) {
6218 types.remove(type);
6219 } else {
6220 types.put(type, uid);
6221 }
6222 }
6223 }
6224
6225 @Override
6226 public void onUserStopped(int userId) {
6227 synchronized (mGlobalLock) {
6228 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6229 mAllowAppSwitchUids.remove(userId);
6230 }
6231 }
6232
6233 @Override
6234 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6235 synchronized (mGlobalLock) {
6236 return ActivityTaskManagerService.this.isGetTasksAllowed(
6237 caller, callingPid, callingUid);
6238 }
6239 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006240
Riddle Hsua0536432019-02-16 00:38:59 +08006241 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006242 @Override
6243 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006244 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006245 mProcessNames.put(proc.mName, proc.mUid, proc);
6246 }
6247 }
6248
Riddle Hsua0536432019-02-16 00:38:59 +08006249 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006250 @Override
6251 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006252 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006253 mProcessNames.remove(name, uid);
6254 }
6255 }
6256
Riddle Hsua0536432019-02-16 00:38:59 +08006257 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006258 @Override
6259 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006260 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006261 if (proc == mHomeProcess) {
6262 mHomeProcess = null;
6263 }
6264 if (proc == mPreviousProcess) {
6265 mPreviousProcess = null;
6266 }
6267 }
6268 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006269
Riddle Hsua0536432019-02-16 00:38:59 +08006270 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006271 @Override
6272 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006273 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006274 return mTopProcessState;
6275 }
6276 }
6277
Riddle Hsua0536432019-02-16 00:38:59 +08006278 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006279 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006280 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006281 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006282 return proc == mHeavyWeightProcess;
6283 }
6284 }
6285
Riddle Hsua0536432019-02-16 00:38:59 +08006286 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006287 @Override
6288 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006289 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006290 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6291 }
6292 }
6293
6294 @Override
6295 public void finishHeavyWeightApp() {
6296 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006297 if (mHeavyWeightProcess != null) {
6298 mHeavyWeightProcess.finishActivities();
6299 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006300 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6301 mHeavyWeightProcess);
6302 }
6303 }
6304
Riddle Hsua0536432019-02-16 00:38:59 +08006305 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006306 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006307 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006308 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006309 return isSleepingLocked();
6310 }
6311 }
6312
6313 @Override
6314 public boolean isShuttingDown() {
6315 synchronized (mGlobalLock) {
6316 return mShuttingDown;
6317 }
6318 }
6319
6320 @Override
6321 public boolean shuttingDown(boolean booted, int timeout) {
6322 synchronized (mGlobalLock) {
6323 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006324 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006325 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006326 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006327 return mStackSupervisor.shutdownLocked(timeout);
6328 }
6329 }
6330
6331 @Override
6332 public void enableScreenAfterBoot(boolean booted) {
6333 synchronized (mGlobalLock) {
6334 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6335 SystemClock.uptimeMillis());
6336 mWindowManager.enableScreenAfterBoot();
6337 updateEventDispatchingLocked(booted);
6338 }
6339 }
6340
6341 @Override
6342 public boolean showStrictModeViolationDialog() {
6343 synchronized (mGlobalLock) {
6344 return mShowDialogs && !mSleeping && !mShuttingDown;
6345 }
6346 }
6347
6348 @Override
6349 public void showSystemReadyErrorDialogsIfNeeded() {
6350 synchronized (mGlobalLock) {
6351 try {
6352 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6353 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6354 + " data partition or your device will be unstable.");
6355 mUiHandler.post(() -> {
6356 if (mShowDialogs) {
6357 AlertDialog d = new BaseErrorDialog(mUiContext);
6358 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6359 d.setCancelable(false);
6360 d.setTitle(mUiContext.getText(R.string.android_system_label));
6361 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6362 d.setButton(DialogInterface.BUTTON_POSITIVE,
6363 mUiContext.getText(R.string.ok),
6364 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6365 d.show();
6366 }
6367 });
6368 }
6369 } catch (RemoteException e) {
6370 }
6371
6372 if (!Build.isBuildConsistent()) {
6373 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6374 mUiHandler.post(() -> {
6375 if (mShowDialogs) {
6376 AlertDialog d = new BaseErrorDialog(mUiContext);
6377 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6378 d.setCancelable(false);
6379 d.setTitle(mUiContext.getText(R.string.android_system_label));
6380 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6381 d.setButton(DialogInterface.BUTTON_POSITIVE,
6382 mUiContext.getText(R.string.ok),
6383 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6384 d.show();
6385 }
6386 });
6387 }
6388 }
6389 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006390
6391 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006392 public void onProcessMapped(int pid, WindowProcessController proc) {
6393 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006394 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006395 }
6396 }
6397
6398 @Override
6399 public void onProcessUnMapped(int pid) {
6400 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006401 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006402 }
6403 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006404
6405 @Override
6406 public void onPackageDataCleared(String name) {
6407 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006408 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006409 mAppWarnings.onPackageDataCleared(name);
6410 }
6411 }
6412
6413 @Override
6414 public void onPackageUninstalled(String name) {
6415 synchronized (mGlobalLock) {
6416 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006417 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006418 }
6419 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006420
6421 @Override
6422 public void onPackageAdded(String name, boolean replacing) {
6423 synchronized (mGlobalLock) {
6424 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6425 }
6426 }
6427
6428 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006429 public void onPackageReplaced(ApplicationInfo aInfo) {
6430 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006431 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006432 }
6433 }
6434
6435 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006436 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6437 synchronized (mGlobalLock) {
6438 return compatibilityInfoForPackageLocked(ai);
6439 }
6440 }
6441
Yunfan Chen75157d72018-07-27 14:47:21 +09006442 /**
6443 * Set the corresponding display information for the process global configuration. To be
6444 * called when we need to show IME on a different display.
6445 *
6446 * @param pid The process id associated with the IME window.
6447 * @param displayId The ID of the display showing the IME.
6448 */
6449 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006450 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006451 // Don't update process-level configuration for Multi-Client IME process since other
6452 // IMEs on other displays will also receive this configuration change due to IME
6453 // services use the same application config/context.
6454 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006455
Yunfan Chen75157d72018-07-27 14:47:21 +09006456 if (pid == MY_PID || pid < 0) {
6457 if (DEBUG_CONFIGURATION) {
6458 Slog.w(TAG,
6459 "Trying to update display configuration for system/invalid process.");
6460 }
6461 return;
6462 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006463 synchronized (mGlobalLock) {
6464 final ActivityDisplay activityDisplay =
6465 mRootActivityContainer.getActivityDisplay(displayId);
6466 if (activityDisplay == null) {
6467 // Call might come when display is not yet added or has been removed.
6468 if (DEBUG_CONFIGURATION) {
6469 Slog.w(TAG, "Trying to update display configuration for non-existing "
6470 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006471 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006472 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006473 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006474 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006475 if (process == null) {
6476 if (DEBUG_CONFIGURATION) {
6477 Slog.w(TAG, "Trying to update display configuration for invalid "
6478 + "process, pid=" + pid);
6479 }
6480 return;
6481 }
lumarkddc77fb2019-06-27 22:22:23 +08006482 process.mIsImeProcess = true;
Yunfan Chencafc7062019-01-22 17:21:32 +09006483 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6484 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006485 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006486
6487 @Override
6488 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006489 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006490 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006491 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6492 if (r != null && r.getActivityStack() != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07006493 r.sendResult(callingUid, resultWho, requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006494 }
6495 }
6496 }
6497
6498 @Override
6499 public void clearPendingResultForActivity(IBinder activityToken,
6500 WeakReference<PendingIntentRecord> pir) {
6501 synchronized (mGlobalLock) {
6502 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6503 if (r != null && r.pendingResults != null) {
6504 r.pendingResults.remove(pir);
6505 }
6506 }
6507 }
6508
6509 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006510 public ActivityTokens getTopActivityForTask(int taskId) {
6511 synchronized (mGlobalLock) {
6512 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6513 if (taskRecord == null) {
6514 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6515 + " Requested task not found");
6516 return null;
6517 }
6518 final ActivityRecord activity = taskRecord.getTopActivity();
6519 if (activity == null) {
6520 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6521 + " Requested activity not found");
6522 return null;
6523 }
6524 if (!activity.attachedToProcess()) {
6525 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6526 + activity);
6527 return null;
6528 }
6529 return new ActivityTokens(activity.appToken, activity.assistToken,
6530 activity.app.getThread());
6531 }
6532 }
6533
6534 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006535 public IIntentSender getIntentSender(int type, String packageName,
6536 int callingUid, int userId, IBinder token, String resultWho,
6537 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6538 Bundle bOptions) {
6539 synchronized (mGlobalLock) {
6540 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6541 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6542 }
6543 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006544
6545 @Override
6546 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6547 synchronized (mGlobalLock) {
6548 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6549 if (r == null) {
6550 return null;
6551 }
6552 if (r.mServiceConnectionsHolder == null) {
6553 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6554 ActivityTaskManagerService.this, r);
6555 }
6556
6557 return r.mServiceConnectionsHolder;
6558 }
6559 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006560
6561 @Override
6562 public Intent getHomeIntent() {
6563 synchronized (mGlobalLock) {
6564 return ActivityTaskManagerService.this.getHomeIntent();
6565 }
6566 }
6567
6568 @Override
6569 public boolean startHomeActivity(int userId, String reason) {
6570 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006571 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006572 }
6573 }
6574
6575 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006576 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006577 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006578 synchronized (mGlobalLock) {
6579 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006580 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006581 }
Chilun8b1f1be2019-03-13 17:14:36 +08006582 }
6583
6584 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006585 public boolean startHomeOnAllDisplays(int userId, String reason) {
6586 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006587 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006588 }
6589 }
6590
Riddle Hsua0536432019-02-16 00:38:59 +08006591 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006592 @Override
6593 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006594 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006595 if (mFactoryTest == FACTORY_TEST_OFF) {
6596 return false;
6597 }
6598 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6599 && wpc.mName.equals(mTopComponent.getPackageName())) {
6600 return true;
6601 }
6602 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6603 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6604 }
6605 }
6606
6607 @Override
6608 public void updateTopComponentForFactoryTest() {
6609 synchronized (mGlobalLock) {
6610 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6611 return;
6612 }
6613 final ResolveInfo ri = mContext.getPackageManager()
6614 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6615 final CharSequence errorMsg;
6616 if (ri != null) {
6617 final ActivityInfo ai = ri.activityInfo;
6618 final ApplicationInfo app = ai.applicationInfo;
6619 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6620 mTopAction = Intent.ACTION_FACTORY_TEST;
6621 mTopData = null;
6622 mTopComponent = new ComponentName(app.packageName, ai.name);
6623 errorMsg = null;
6624 } else {
6625 errorMsg = mContext.getResources().getText(
6626 com.android.internal.R.string.factorytest_not_system);
6627 }
6628 } else {
6629 errorMsg = mContext.getResources().getText(
6630 com.android.internal.R.string.factorytest_no_action);
6631 }
6632 if (errorMsg == null) {
6633 return;
6634 }
6635
6636 mTopAction = null;
6637 mTopData = null;
6638 mTopComponent = null;
6639 mUiHandler.post(() -> {
6640 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6641 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006642 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006643 });
6644 }
6645 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006646
Riddle Hsua0536432019-02-16 00:38:59 +08006647 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006648 @Override
6649 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6650 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006651 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006652 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006653 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654
6655 wpc.clearRecentTasks();
6656 wpc.clearActivities();
6657
6658 if (wpc.isInstrumenting()) {
6659 finishInstrumentationCallback.run();
6660 }
6661
Jorim Jaggid0752812018-10-16 16:07:20 +02006662 if (!restarting && hasVisibleActivities) {
6663 mWindowManager.deferSurfaceLayout();
6664 try {
6665 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6666 // If there was nothing to resume, and we are not already restarting
6667 // this process, but there is a visible activity that is hosted by the
6668 // process...then make sure all visible activities are running, taking
6669 // care of restarting this process.
6670 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6671 !PRESERVE_WINDOWS);
6672 }
6673 } finally {
6674 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006675 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006676 }
6677 }
6678 }
6679
6680 @Override
6681 public void closeSystemDialogs(String reason) {
6682 enforceNotIsolatedCaller("closeSystemDialogs");
6683
6684 final int pid = Binder.getCallingPid();
6685 final int uid = Binder.getCallingUid();
6686 final long origId = Binder.clearCallingIdentity();
6687 try {
6688 synchronized (mGlobalLock) {
6689 // Only allow this from foreground processes, so that background
6690 // applications can't abuse it to prevent system UI from being shown.
6691 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006692 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006693 if (!proc.isPerceptible()) {
6694 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6695 + " from background process " + proc);
6696 return;
6697 }
6698 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006699 mWindowManager.closeSystemDialogs(reason);
6700
Wale Ogunwaled32da472018-11-16 07:19:28 -08006701 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006702 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006703 // Call into AM outside the synchronized block.
6704 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006705 } finally {
6706 Binder.restoreCallingIdentity(origId);
6707 }
6708 }
6709
6710 @Override
6711 public void cleanupDisabledPackageComponents(
6712 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6713 synchronized (mGlobalLock) {
6714 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006715 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006716 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006717 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 mStackSupervisor.scheduleIdleLocked();
6719 }
6720
6721 // Clean-up disabled tasks
6722 getRecentTasks().cleanupDisabledPackageTasksLocked(
6723 packageName, disabledClasses, userId);
6724 }
6725 }
6726
6727 @Override
6728 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6729 int userId) {
6730 synchronized (mGlobalLock) {
6731
6732 boolean didSomething =
6733 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006734 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006735 null, doit, evenPersistent, userId);
6736 return didSomething;
6737 }
6738 }
6739
6740 @Override
6741 public void resumeTopActivities(boolean scheduleIdle) {
6742 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006743 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006744 if (scheduleIdle) {
6745 mStackSupervisor.scheduleIdleLocked();
6746 }
6747 }
6748 }
6749
Riddle Hsua0536432019-02-16 00:38:59 +08006750 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 @Override
6752 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006753 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006754 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6755 }
6756 }
6757
Riddle Hsua0536432019-02-16 00:38:59 +08006758 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 @Override
6760 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006761 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006762 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006763 }
6764 }
6765
6766 @Override
6767 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6768 try {
6769 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6770 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6771 }
6772 } catch (RemoteException ex) {
6773 throw new SecurityException("Fail to check is caller a privileged app", ex);
6774 }
6775
6776 synchronized (mGlobalLock) {
6777 final long ident = Binder.clearCallingIdentity();
6778 try {
6779 if (mAmInternal.shouldConfirmCredentials(userId)) {
6780 if (mKeyguardController.isKeyguardLocked()) {
6781 // Showing launcher to avoid user entering credential twice.
6782 startHomeActivity(currentUserId, "notifyLockedProfile");
6783 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006784 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006785 }
6786 } finally {
6787 Binder.restoreCallingIdentity(ident);
6788 }
6789 }
6790 }
6791
6792 @Override
6793 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6794 mAmInternal.enforceCallingPermission(
6795 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6796
6797 synchronized (mGlobalLock) {
6798 final long ident = Binder.clearCallingIdentity();
6799 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006800 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6801 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006802 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6804 UserHandle.CURRENT);
6805 } finally {
6806 Binder.restoreCallingIdentity(ident);
6807 }
6808 }
6809 }
6810
6811 @Override
6812 public void writeActivitiesToProto(ProtoOutputStream proto) {
6813 synchronized (mGlobalLock) {
6814 // The output proto of "activity --proto activities"
6815 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006816 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006817 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6818 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 }
6820 }
6821
6822 @Override
6823 public void saveANRState(String reason) {
6824 synchronized (mGlobalLock) {
6825 final StringWriter sw = new StringWriter();
6826 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6827 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6828 if (reason != null) {
6829 pw.println(" Reason: " + reason);
6830 }
6831 pw.println();
6832 getActivityStartController().dump(pw, " ", null);
6833 pw.println();
6834 pw.println("-------------------------------------------------------------------------------");
6835 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6836 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6837 "" /* header */);
6838 pw.println();
6839 pw.close();
6840
6841 mLastANRState = sw.toString();
6842 }
6843 }
6844
6845 @Override
6846 public void clearSavedANRState() {
6847 synchronized (mGlobalLock) {
6848 mLastANRState = null;
6849 }
6850 }
6851
6852 @Override
6853 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6854 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6855 synchronized (mGlobalLock) {
6856 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6857 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6858 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6859 dumpLastANRLocked(pw);
6860 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6861 dumpLastANRTracesLocked(pw);
6862 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6863 dumpActivityStarterLocked(pw, dumpPackage);
6864 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6865 dumpActivityContainersLocked(pw);
6866 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6867 if (getRecentTasks() != null) {
6868 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6869 }
6870 }
6871 }
6872 }
6873
6874 @Override
6875 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6876 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6877 int wakefulness) {
6878 synchronized (mGlobalLock) {
6879 if (mHomeProcess != null && (dumpPackage == null
6880 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6881 if (needSep) {
6882 pw.println();
6883 needSep = false;
6884 }
6885 pw.println(" mHomeProcess: " + mHomeProcess);
6886 }
6887 if (mPreviousProcess != null && (dumpPackage == null
6888 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6889 if (needSep) {
6890 pw.println();
6891 needSep = false;
6892 }
6893 pw.println(" mPreviousProcess: " + mPreviousProcess);
6894 }
6895 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6896 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6897 StringBuilder sb = new StringBuilder(128);
6898 sb.append(" mPreviousProcessVisibleTime: ");
6899 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6900 pw.println(sb);
6901 }
6902 if (mHeavyWeightProcess != null && (dumpPackage == null
6903 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6904 if (needSep) {
6905 pw.println();
6906 needSep = false;
6907 }
6908 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6909 }
6910 if (dumpPackage == null) {
6911 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006912 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006913 }
6914 if (dumpAll) {
6915 if (dumpPackage == null) {
6916 pw.println(" mConfigWillChange: "
6917 + getTopDisplayFocusedStack().mConfigWillChange);
6918 }
6919 if (mCompatModePackages.getPackages().size() > 0) {
6920 boolean printed = false;
6921 for (Map.Entry<String, Integer> entry
6922 : mCompatModePackages.getPackages().entrySet()) {
6923 String pkg = entry.getKey();
6924 int mode = entry.getValue();
6925 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6926 continue;
6927 }
6928 if (!printed) {
6929 pw.println(" mScreenCompatPackages:");
6930 printed = true;
6931 }
6932 pw.println(" " + pkg + ": " + mode);
6933 }
6934 }
6935 }
6936
6937 if (dumpPackage == null) {
6938 pw.println(" mWakefulness="
6939 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006940 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006941 if (mRunningVoice != null) {
6942 pw.println(" mRunningVoice=" + mRunningVoice);
6943 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6944 }
6945 pw.println(" mSleeping=" + mSleeping);
6946 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6947 pw.println(" mVrController=" + mVrController);
6948 }
6949 if (mCurAppTimeTracker != null) {
6950 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6951 }
6952 if (mAllowAppSwitchUids.size() > 0) {
6953 boolean printed = false;
6954 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6955 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6956 for (int j = 0; j < types.size(); j++) {
6957 if (dumpPackage == null ||
6958 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6959 if (needSep) {
6960 pw.println();
6961 needSep = false;
6962 }
6963 if (!printed) {
6964 pw.println(" mAllowAppSwitchUids:");
6965 printed = true;
6966 }
6967 pw.print(" User ");
6968 pw.print(mAllowAppSwitchUids.keyAt(i));
6969 pw.print(": Type ");
6970 pw.print(types.keyAt(j));
6971 pw.print(" = ");
6972 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6973 pw.println();
6974 }
6975 }
6976 }
6977 }
6978 if (dumpPackage == null) {
6979 if (mController != null) {
6980 pw.println(" mController=" + mController
6981 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6982 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006983 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6984 pw.println(" mLaunchingActivityWakeLock="
6985 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006986 }
6987
6988 return needSep;
6989 }
6990 }
6991
6992 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006993 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6994 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006995 synchronized (mGlobalLock) {
6996 if (dumpPackage == null) {
6997 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6998 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006999 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7000 if (mRunningVoice != null) {
7001 final long vrToken = proto.start(
7002 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7003 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7004 mRunningVoice.toString());
7005 mVoiceWakeLock.writeToProto(
7006 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7007 proto.end(vrToken);
7008 }
7009 mVrController.writeToProto(proto,
7010 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007011 if (mController != null) {
7012 final long token = proto.start(CONTROLLER);
7013 proto.write(CONTROLLER, mController.toString());
7014 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7015 proto.end(token);
7016 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007017 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7018 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7019 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007020 }
7021
7022 if (mHomeProcess != null && (dumpPackage == null
7023 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007024 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 }
7026
7027 if (mPreviousProcess != null && (dumpPackage == null
7028 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007029 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7031 }
7032
7033 if (mHeavyWeightProcess != null && (dumpPackage == null
7034 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007035 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007036 }
7037
7038 for (Map.Entry<String, Integer> entry
7039 : mCompatModePackages.getPackages().entrySet()) {
7040 String pkg = entry.getKey();
7041 int mode = entry.getValue();
7042 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7043 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7044 proto.write(PACKAGE, pkg);
7045 proto.write(MODE, mode);
7046 proto.end(compatToken);
7047 }
7048 }
7049
7050 if (mCurAppTimeTracker != null) {
7051 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7052 }
7053
7054 }
7055 }
7056
7057 @Override
7058 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7059 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7060 boolean dumpFocusedStackOnly) {
Riddle Hsud7cd8ed2019-07-16 18:19:01 +08007061 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti, dumpAll,
7062 dumpVisibleStacksOnly, dumpFocusedStackOnly);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007063 }
7064
7065 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007066 public void dumpForOom(PrintWriter pw) {
7067 synchronized (mGlobalLock) {
7068 pw.println(" mHomeProcess: " + mHomeProcess);
7069 pw.println(" mPreviousProcess: " + mPreviousProcess);
7070 if (mHeavyWeightProcess != null) {
7071 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7072 }
7073 }
7074 }
7075
7076 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 public boolean canGcNow() {
7078 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007079 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007080 }
7081 }
7082
Riddle Hsua0536432019-02-16 00:38:59 +08007083 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007084 @Override
7085 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007086 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007087 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007088 return top != null ? top.app : null;
7089 }
7090 }
7091
Riddle Hsua0536432019-02-16 00:38:59 +08007092 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 @Override
7094 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007095 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007096 if (mRootActivityContainer != null) {
7097 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007098 }
7099 }
7100 }
7101
7102 @Override
7103 public void scheduleDestroyAllActivities(String reason) {
7104 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007105 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007106 }
7107 }
7108
7109 @Override
7110 public void removeUser(int userId) {
7111 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007112 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007113 }
7114 }
7115
7116 @Override
7117 public boolean switchUser(int userId, UserState userState) {
7118 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007119 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007120 }
7121 }
7122
7123 @Override
7124 public void onHandleAppCrash(WindowProcessController wpc) {
7125 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007126 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007129
7130 @Override
7131 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7132 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007133 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007134 }
7135 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007136
Riddle Hsua0536432019-02-16 00:38:59 +08007137 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007138 @Override
7139 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007140 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007141 }
7142
Riddle Hsua0536432019-02-16 00:38:59 +08007143 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007144 @Override
7145 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007146 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007147 }
7148
Riddle Hsua0536432019-02-16 00:38:59 +08007149 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007150 @Override
7151 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007152 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007153 }
7154
Riddle Hsua0536432019-02-16 00:38:59 +08007155 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007156 @Override
7157 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007158 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007159 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007160
7161 @Override
7162 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007163 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007164 mPendingTempWhitelist.put(uid, tag);
7165 }
7166 }
7167
7168 @Override
7169 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007170 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007171 mPendingTempWhitelist.remove(uid);
7172 }
7173 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007174
7175 @Override
7176 public boolean handleAppCrashInActivityController(String processName, int pid,
7177 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7178 Runnable killCrashingAppCallback) {
7179 synchronized (mGlobalLock) {
7180 if (mController == null) {
7181 return false;
7182 }
7183
7184 try {
7185 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7186 stackTrace)) {
7187 killCrashingAppCallback.run();
7188 return true;
7189 }
7190 } catch (RemoteException e) {
7191 mController = null;
7192 Watchdog.getInstance().setActivityController(null);
7193 }
7194 return false;
7195 }
7196 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007197
7198 @Override
7199 public void removeRecentTasksByPackageName(String packageName, int userId) {
7200 synchronized (mGlobalLock) {
7201 mRecentTasks.removeTasksByPackageName(packageName, userId);
7202 }
7203 }
7204
7205 @Override
7206 public void cleanupRecentTasksForUser(int userId) {
7207 synchronized (mGlobalLock) {
7208 mRecentTasks.cleanupLocked(userId);
7209 }
7210 }
7211
7212 @Override
7213 public void loadRecentTasksForUser(int userId) {
7214 synchronized (mGlobalLock) {
7215 mRecentTasks.loadUserRecentsLocked(userId);
7216 }
7217 }
7218
7219 @Override
7220 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7221 synchronized (mGlobalLock) {
7222 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7223 }
7224 }
7225
7226 @Override
7227 public void flushRecentTasks() {
7228 mRecentTasks.flush();
7229 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007230
7231 @Override
7232 public WindowProcessController getHomeProcess() {
7233 synchronized (mGlobalLock) {
7234 return mHomeProcess;
7235 }
7236 }
7237
7238 @Override
7239 public WindowProcessController getPreviousProcess() {
7240 synchronized (mGlobalLock) {
7241 return mPreviousProcess;
7242 }
7243 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007244
7245 @Override
7246 public void clearLockedTasks(String reason) {
7247 synchronized (mGlobalLock) {
7248 getLockTaskController().clearLockedTasks(reason);
7249 }
7250 }
7251
7252 @Override
7253 public void updateUserConfiguration() {
7254 synchronized (mGlobalLock) {
7255 final Configuration configuration = new Configuration(getGlobalConfiguration());
7256 final int currentUserId = mAmInternal.getCurrentUserId();
7257 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7258 configuration, currentUserId, Settings.System.canWrite(mContext));
7259 updateConfigurationLocked(configuration, null /* starting */,
7260 false /* initLocale */, false /* persistent */, currentUserId,
7261 false /* deferResume */);
7262 }
7263 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007264
7265 @Override
7266 public boolean canShowErrorDialogs() {
7267 synchronized (mGlobalLock) {
7268 return mShowDialogs && !mSleeping && !mShuttingDown
7269 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7270 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7271 mAmInternal.getCurrentUserId())
7272 && !(UserManager.isDeviceInDemoMode(mContext)
7273 && mAmInternal.getCurrentUser().isDemo());
7274 }
7275 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007276
7277 @Override
7278 public void setProfileApp(String profileApp) {
7279 synchronized (mGlobalLock) {
7280 mProfileApp = profileApp;
7281 }
7282 }
7283
7284 @Override
7285 public void setProfileProc(WindowProcessController wpc) {
7286 synchronized (mGlobalLock) {
7287 mProfileProc = wpc;
7288 }
7289 }
7290
7291 @Override
7292 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7293 synchronized (mGlobalLock) {
7294 mProfilerInfo = profilerInfo;
7295 }
7296 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007297
7298 @Override
7299 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7300 synchronized (mGlobalLock) {
7301 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7302 }
7303 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007304
7305 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007306 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7307 boolean reducedResolution) {
7308 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7309 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007310 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007311
7312 @Override
7313 public boolean isUidForeground(int uid) {
7314 synchronized (mGlobalLock) {
7315 return ActivityTaskManagerService.this.isUidForeground(uid);
7316 }
7317 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007318
7319 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007320 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007321 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007322 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007323 }
7324 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007325
7326 @Override
7327 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007328 // Translate package names into UIDs
7329 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007330 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007331 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7332 if (uid >= 0) {
7333 result.add(uid);
7334 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007335 }
7336 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007337 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007338 }
7339 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007340 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007341}